Functions: Difference between revisions

From NEOSYS Dev Wiki
Jump to navigationJump to search
(Created page with " <html> <!DOCTYPE html> <html> <head> </head> <body> <!-- highlight.js for c++ syntax highlighting --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/cpp.min.js"></script> <!-- done below <script>hljs.highlightAll();</s...")
 
No edit summary
Line 249: Line 249:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td></td><td>var v1;</td><td>Create an unassigned var.</p>
<tr><td></td><td>var v1;</td><td><p>Create an unassigned var.
The var must be assigned before being used otherwise a runtime error VarUnassigned is thrown. Silent "use before assign" bugs cannot occur.</p>
Allowing unassigned variables allows them to be assigned conditionally in if/else statements and provided as outbound arguments of a function call.</p>
</p>
</p>
Use "let" instead of "var" as a shorthand way of writing "const var" whereever possible.
<p>Unassigned variables can be assigned conditionally in if/else statements or used as outbound arguments of function calls.
</p>
A runtime error is thrown if a var is used before being assigned so silent "use before assign" bugs cannot occur.


<pre><code class='hljs-ncdecl language-javascript'>var client;                     // Unassigned var
<pre><code class='hljs-ncdecl language-javascript'>var client; // Unassigned var
let client_code = "SB001";      // Constant var
if (not read(client from "xo_clients", "SB001")) ...</code></pre>
var clients    = "xo_clients"; // Variable var
 
if (not read(client from clients, client_code)) ...</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>var v1 = expression;</td><td>Assign a var using a literal or an expression. Alternatively, use "let" instead of "var" as a shorthand way of writing "const var" where appropriate.
<tr><td></td><td>var v1 = expression;</td><td><p>Assign a var using a literal or an expression.
</p>
Use "let" instead of "var" wherever possible as a shorthand way of writing "const var".


<pre><code class='hljs-ncdecl language-javascript'>var v1 = 42;                // Integer
<pre><code class='hljs-ncdecl language-javascript'>var v1 = 42;                // Integer
Line 283: Line 282:


</td></tr>
</td></tr>
<tr><td>if</td><td>v1.assigned()</td><td>Returns: True if the var is assigned, otherwise false</td></tr>
<tr><td>if</td><td>v1.assigned()</td><td>
<tr><td>if</td><td>v1.unassigned()</td><td>Returns: True if the var is unassigned, otherwise false</td></tr>
<em>Returns:</em> True if the var is assigned, otherwise false</td></tr>
<tr><td>var=</td><td>v2.or_default(defaultvalue)</td><td>Returns: A copy of the var if it is assigned or the default value if it is not.</p>
<tr><td>if</td><td>v1.unassigned()</td><td>
Can be used to handle optional arguments in functions.</p>
<em>Returns:</em> True if the var is unassigned, otherwise false</td></tr>
<em>defaultvalue:</em> Cannot be unassigned.
<tr><td>var=</td><td>v2.or_default(defaultvalue)</td><td>
<p><em>Returns:</em> A copy of the var if it is assigned or the default value if it is not.
</p>
<p>Can be used to handle optional arguments in functions.
</p>
<p><em>defaultvalue:</em> Cannot be unassigned.


<pre><code class='hljs-ncdecl language-javascript'>var v1; // Unassigned
<pre><code class='hljs-ncdecl language-javascript'>var v1; // Unassigned
Line 294: Line 298:
var v3 = or_default(v1, "abc");</code></pre>
var v3 = or_default(v1, "abc");</code></pre>


<em>Mutator:</em> defaulter()</p>
 
</p>
<p><em>Mutator:</em> defaulter()
</p>
</td></tr>
</td></tr>
<tr><td></td><td>v1.defaulter(defaultvalue)</td><td>If the var is unassigned then assign the default value to it, otherwise do nothing.</p>
<tr><td></td><td>v1.defaulter(defaultvalue)</td><td><p>If the var is unassigned then assign the default value to it, otherwise do nothing.
</p>
<em>defaultvalue:</em> Cannot be unassigned.
<em>defaultvalue:</em> Cannot be unassigned.


Line 305: Line 313:


</td></tr>
</td></tr>
<tr><td></td><td>v1.swap(io v2)</td><td>Swap the contents of one var with another.</p>
<tr><td></td><td>v1.swap(io v2)</td><td><p>Swap the contents of one var with another.
Useful for stashing large strings quickly. They are moved using pointers without making copies or allocating memory.</p>
</p>
<p>Useful for stashing large strings quickly. They are moved using pointers without making copies or allocating memory.
</p>
Eiher or both variables may be unassigned.
Eiher or both variables may be unassigned.


Line 316: Line 326:


</td></tr>
</td></tr>
<tr><td>var=</td><td>v2.move()</td><td>Force the contents of a var to be moved instead of copied. The moved var becomes an empty string.</p>
<tr><td>var=</td><td>v2.move()</td><td><p>Force the contents of a var to be moved instead of copied. The moved var becomes an empty string.
This allows large strings to be handled efficiently. They are moved using pointers without making copies or allocating memory.</p>
</p>
<p>This allows large strings to be handled efficiently. They are moved using pointers without making copies or allocating memory.
</p>
The moved var must be assigned otherwise a VarUnassigned error is thrown.
The moved var must be assigned otherwise a VarUnassigned error is thrown.


Line 326: Line 338:


</td></tr>
</td></tr>
<tr><td>var=</td><td>v2.clone()</td><td>Returns a copy of the var.</p>
<tr><td>var=</td><td>v2.clone()</td><td><p>Returns a copy of the var.
</p>
The cloned var may be unassigned, in which case the copy will be unassigned too.
The cloned var may be unassigned, in which case the copy will be unassigned too.


Line 335: Line 348:


</td></tr>
</td></tr>
<tr><td>var=</td><td>v1.dump()</td><td>Return a string describing internal data of a var.</p>
<tr><td>var=</td><td>v1.dump()</td><td><p>Return a string describing internal data of a var.
If the str is located on the heap then its address is given.</p>
</p>
<em>typ:</em></p>
<p>If the str is located on the heap then its address is given.
0x01 str is available.</p>
</p>
0x02 int is available.</p>
<p><em>typ:</em>
0x04 dbl is available.</p>
</p>
0x08 nan: str is not a number.</p>
<p>0x01 str is available.
</p>
<p>0x02 int is available.
</p>
<p>0x04 dbl is available.
</p>
<p>0x08 nan: str is not a number.
</p>
0x16 osfile: str, int and dbl have special meaning.
0x16 osfile: str, int and dbl have special meaning.


Line 355: Line 375:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>v1.isnum()</td><td>Checks if a var is numeric.</p>
<tr><td>if</td><td>v1.isnum()</td><td><p>Checks if a var is numeric.
<em>Returns:</em> True if a var holds a double, an integer, or a string that is defined as numeric.</p>
</p>
<p><em>Returns:</em> True if a var holds a double, an integer, or a string that is defined as numeric.
</p>
A string is defined as numeric only if it consists of one or more digits 0-9, with an optional decimal point "." placed anywhere, with an optional + or - sign prefix, or it is the empty string "", which is defined to be zero.
A string is defined as numeric only if it consists of one or more digits 0-9, with an optional decimal point "." placed anywhere, with an optional + or - sign prefix, or it is the empty string "", which is defined to be zero.


Line 366: Line 388:


</td></tr>
</td></tr>
<tr><td>var=</td><td>v1.num()</td><td>Returns a copy of the var if it is numeric or 0 otherwise.</p>
<tr><td>var=</td><td>v1.num()</td><td><p>Returns a copy of the var if it is numeric or 0 otherwise.
<em>Returns:</em> A guaranteed numeric var</p>
</p>
<p><em>Returns:</em> A guaranteed numeric var
</p>
Allows working numerically with data that may be non-numeric.
Allows working numerically with data that may be non-numeric.


Line 374: Line 398:


</td></tr>
</td></tr>
<tr><td>var=</td><td>v2 + v3</td><td>Addition</p>
<tr><td>var=</td><td>v2 + v3</td><td><p>Addition
Attempts to perform numeric operations on non-numeric strings will throw a runtime error VarNonNumeric.</p>
</p>
Floating point numbers are implicitly converted to strings with no more than 12 significant digits of precision. This practically eliminates all floatng point rounding errors.</p>
<p>Attempts to perform numeric operations on non-numeric strings will throw a runtime error VarNonNumeric.
Internally, 0.1 + 0.2 looks like this using doubles.</p>
</p>
<p>Floating point numbers are implicitly converted to strings with no more than 12 significant digits of precision. This practically eliminates all floatng point rounding errors.
</p>
<p>Internally, 0.1 + 0.2 looks like this using doubles.
</p>
0.10000000000000003 + 0.20000000000000004 -> 0.30000000000000004
0.10000000000000003 + 0.20000000000000004 -> 0.30000000000000004


Line 427: Line 455:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>""_var</td><td>The literal suffix "_var" allows dynamic arrays to be seamlessly embedded in code using a predefined set of visible equivalents of unprintable field mark characters as follows:</p>
<tr><td>var=</td><td>""_var</td><td><p>The literal suffix "_var" allows dynamic arrays to be seamlessly embedded in code using a predefined set of visible equivalents of unprintable field mark characters as follows:
` = RM, Record mark</p>
</p>
^ = FM, Field mark</p>
<p>` = RM, Record mark
] = VM, Value mark</p>
</p>
} = SM, Subvalue mark</p>
<p>^ = FM, Field mark
| = TM, Text mark</p>
</p>
<p>] = VM, Value mark
</p>
<p>} = SM, Subvalue mark
</p>
<p>| = TM, Text mark
</p>
~ = ST, Subtext mark
~ = ST, Subtext mark


Line 443: Line 477:


</td></tr>
</td></tr>
<tr><td>var=</td><td>v2(fieldno);      v1(fieldno) = v2</td><td>Dynamic array - field extraction, update and append:</p>
<tr><td>var=</td><td>v2(fieldno);      v1(fieldno) = v2</td><td><p>Dynamic array - field extraction, update and append:
See also inserter() and remover().
</p>
<p>See also inserter() and remover().


<pre><code class='hljs-ncdecl language-javascript'>var v1 = "aa^bb"_var;
<pre><code class='hljs-ncdecl language-javascript'>var v1 = "aa^bb"_var;
Line 451: Line 486:
v1(-1) = "55"; // v1 -> "aa^bb^^44^55"_var</code></pre>
v1(-1) = "55"; // v1 -> "aa^bb^^44^55"_var</code></pre>


Field access:</p>
Field access:
It is recommended to use "v1.f(fieldno)" syntax using a ".f(" prefix to access fields in expressions instead of plain "v1(fieldno)". The former syntax (using .f()) will always compile whereas the latter does not compile in all contexts. It will compile only if being called on a constant var or in a location which requires a var. This is due to C++ not making a clear distinction between usage on the left and right side of assignment operator =.</p>
</p>
<p>It is recommended to use "v1.f(fieldno)" syntax using a ".f(" prefix to access fields in expressions instead of plain "v1(fieldno)". The former syntax (using .f()) will always compile whereas the latter does not compile in all contexts. It will compile only if being called on a constant var or in a location which requires a var. This is due to C++ not making a clear distinction between usage on the left and right side of assignment operator =.
</p>
Furthermore using plain round brackets without the leading .f can be confused with function call syntax.
Furthermore using plain round brackets without the leading .f can be confused with function call syntax.


Line 460: Line 497:


</td></tr>
</td></tr>
<tr><td>var=</td><td>v2(fieldno, valueno);      v1(fieldno, valueno) = v2</td><td>Dynamic array - value update and append</p>
<tr><td>var=</td><td>v2(fieldno, valueno);      v1(fieldno, valueno) = v2</td><td><p>Dynamic array - value update and append
</p>
See also inserter() and remover().
See also inserter() and remover().


Line 480: Line 518:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>v2 ^ v3</td><td>String concatention operator ^</p>
<tr><td>var=</td><td>v2 ^ v3</td><td><p>String concatention operator ^
At least one side must be a var.</p>
</p>
"aa" ^ "22" will not compile but "aa" "22" will.</p>
<p>At least one side must be a var.
</p>
<p>"aa" ^ "22" will not compile but "aa" "22" will.
</p>
Floating point numbers are implicitly converted to strings with no more than 12 significant digits of precision. This practically eliminates all floatng point rounding errors.
Floating point numbers are implicitly converted to strings with no more than 12 significant digits of precision. This practically eliminates all floatng point rounding errors.


Line 494: Line 535:
v1 ^= 22; // v1 -> "aa22"</code></pre>
v1 ^= 22; // v1 -> "aa22"</code></pre>
</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.round(ndecimals = 0)</td><td>Convert a number into a string after rounding it to a given number of decimal places.</p>
<tr><td>var=</td><td>varnum.round(ndecimals = 0)</td><td><p>Convert a number into a string after rounding it to a given number of decimal places.
Trailing zeros are not omitted. A leading "0." is shown where appropriate.</p>
</p>
0.5 always rounds away from zero. i.e. 1.5 -> 2 and -2.5 -> -3</p>
<p>Trailing zeros are not omitted. A leading "0." is shown where appropriate.
<em>var:</em> The number to be converted.</p>
</p>
<em>ndecimals:</em> Determines how many decimal places are shown to the right of the decimal point or, if ndecimals is negative, how many 0's to the left of it.</p>
<p>0.5 always rounds away from zero. i.e. 1.5 -> 2 and -2.5 -> -3
</p>
<p><em>var:</em> The number to be converted.
</p>
<p><em>ndecimals:</em> Determines how many decimal places are shown to the right of the decimal point or, if ndecimals is negative, how many 0's to the left of it.
</p>
<em>Returns:</em> A var containing an ASCII string of digits with a leading "-" if negative, and a decimal point "." if ndecimals is > 0.
<em>Returns:</em> A var containing an ASCII string of digits with a leading "-" if negative, and a decimal point "." if ndecimals is > 0.


Line 520: Line 566:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::chr(num)</td><td>Get a char given an integer 0-255.</p>
<tr><td>var=</td><td>var::chr(num)</td><td><p>Get a char given an integer 0-255.
<em>Returns:</em> A string containing a single char</p>
</p>
<p><em>Returns:</em> A string containing a single char
</p>
0-127 -> ASCII, 128-255 -> invalid UTF-8 which cannot be written to the database or used in many exodus string operations
0-127 -> ASCII, 128-255 -> invalid UTF-8 which cannot be written to the database or used in many exodus string operations


Line 529: Line 577:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::textchr(num)</td><td>Get a Unicode character given a Unicode Code Point (Number)</p>
<tr><td>var=</td><td>var::textchr(num)</td><td><p>Get a Unicode character given a Unicode Code Point (Number)
</p>
<em>Returns:</em> A single Unicode character in UTF8 encoding.
<em>Returns:</em> A single Unicode character in UTF8 encoding.


Line 537: Line 586:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::textchrname(unicode_code_point)</td><td>Get a Unicode character name</p>
<tr><td>var=</td><td>var::textchrname(unicode_code_point)</td><td><p>Get a Unicode character name
<em>unicode_code_point:</em> 0 - 0x10FFFF.</p>
</p>
<p><em>unicode_code_point:</em> 0 - 0x10FFFF.
</p>
<em>Returns:</em> Text of the name or "" if not a valid Unicode Code Point
<em>Returns:</em> Text of the name or "" if not a valid Unicode Code Point


Line 546: Line 597:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.str(num)</td><td>Get a string of repeated substrings.</p>
<tr><td>var=</td><td>varstr.str(num)</td><td><p>Get a string of repeated substrings.
<em>var:</em> The substring to be repeated</p>
</p>
<em>num:</em> How many times to repeat the substring</p>
<p><em>var:</em> The substring to be repeated
</p>
<p><em>num:</em> How many times to repeat the substring
</p>
<em>Returns:</em> A string
<em>Returns:</em> A string


Line 556: Line 610:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::space(nspaces)</td><td>Get a string containing a given number of spaces.</p>
<tr><td>var=</td><td>var::space(nspaces)</td><td><p>Get a string containing a given number of spaces.
<em>nspaces:</em> The number of spaces required.</p>
</p>
<p><em>nspaces:</em> The number of spaces required.
</p>
<em>Returns:</em> A string of space chars.
<em>Returns:</em> A string of space chars.


Line 565: Line 621:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.numberinwords(locale = "")</td><td>Returns: A string representing a given number written in words instead of digits.</p>
<tr><td>var=</td><td>varnum.numberinwords(locale = "")</td><td>
<p><em>Returns:</em> A string representing a given number written in words instead of digits.
</p>
<em>locale:</em> e.g. en_GB, ar_AE, el_CY, es_US, fr_FR etc or a language name e.g. "french".
<em>locale:</em> e.g. en_GB, ar_AE, el_CY, es_US, fr_FR etc or a language name e.g. "french".


Line 577: Line 635:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>strvar.at(pos1)</td><td>Get a single char from a string.</p>
<tr><td>var=</td><td>strvar.at(pos1)</td><td><p>Get a single char from a string.
<em>pos1:</em> First char is 1. Last char is -1.</p>
</p>
<p><em>pos1:</em> First char is 1. Last char is -1.
</p>
<em>Returns:</em> A single char if pos1 ± the length of the string, or "" if greater. Returns the first char if pos1 is 0 or (-pos1) > length.
<em>Returns:</em> A single char if pos1 ± the length of the string, or "" if greater. Returns the first char if pos1 is 0 or (-pos1) > length.


Line 586: Line 646:
var v4 = v1.at(4);  // ""</code></pre>
var v4 = v1.at(4);  // ""</code></pre>
</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.ord()</td><td>Get the char number of a char</p>
<tr><td>var=</td><td>strvar.ord()</td><td><p>Get the char number of a char
<em>Returns:</em> A number between 0 and 255.</p>
</p>
If given a string, then only the first char is considered.</p>
<p><em>Returns:</em> A number between 0 and 255.
</p>
<p>If given a string, then only the first char is considered.
</p>
Equivalent to ord() in php
Equivalent to ord() in php


Line 596: Line 659:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.textord()</td><td>Get the Unicode Code Point of a Unicode character.</p>
<tr><td>var=</td><td>strvar.textord()</td><td><p>Get the Unicode Code Point of a Unicode character.
<em>var:</em> A UTF-8 string. Only the first Unicode character is considered.</p>
</p>
<em>Returns:</em> A number 0 to 0x10FFFF.</p>
<p><em>var:</em> A UTF-8 string. Only the first Unicode character is considered.
</p>
<p><em>Returns:</em> A number 0 to 0x10FFFF.
</p>
Equivalent to ord() in python and ruby, mb_ord() php.
Equivalent to ord() in python and ruby, mb_ord() php.


Line 606: Line 672:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.len()</td><td>Get the length of a source string in number of chars</p>
<tr><td>var=</td><td>strvar.len()</td><td><p>Get the length of a source string in number of chars
</p>
<em>Returns:</em> A number
<em>Returns:</em> A number


Line 614: Line 681:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.empty()</td><td>Checks if the var is an empty string.</p>
<tr><td>if</td><td>strvar.empty()</td><td><p>Checks if the var is an empty string.
<em>Returns:</em> True if it is empty amd false if not.</p>
</p>
This is a shorthand and more expressive way of writing 'if (var == "")' or 'if (var.len() == 0)' or 'if (not var.len())'</p>
<p><em>Returns:</em> True if it is empty amd false if not.
</p>
<p>This is a shorthand and more expressive way of writing 'if (var == "")' or 'if (var.len() == 0)' or 'if (not var.len())'
</p>
Note that 'if (var.empty())' is not exactly the same as 'if (not var)' because 'if (var("0.0")' is also defined as false. If a string can be converted to 0 then it is considered to be false. Contrast this with common scripting languages where 'if (var("0"))' is defined to be true.
Note that 'if (var.empty())' is not exactly the same as 'if (not var)' because 'if (var("0.0")' is also defined as false. If a string can be converted to 0 then it is considered to be false. Contrast this with common scripting languages where 'if (var("0"))' is defined to be true.


Line 625: Line 695:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.textwidth()</td><td>Count the number of output columns required for a given source string.</p>
<tr><td>var=</td><td>strvar.textwidth()</td><td><p>Count the number of output columns required for a given source string.
<em>Returns:</em> A number</p>
</p>
Allows wide multi-column Unicode characters that occupy more than one space in a text file or terminal screen.</p>
<p><em>Returns:</em> A number
Reduces combining characters to a single column. e.g. "e" followed by grave accent is multiple bytes but only occupies one output column.</p>
</p>
<p>Allows wide multi-column Unicode characters that occupy more than one space in a text file or terminal screen.
</p>
<p>Reduces combining characters to a single column. e.g. "e" followed by grave accent is multiple bytes but only occupies one output column.
</p>
Does not properly calculate all possible combining sequences of graphemes e.g. face followed by colour
Does not properly calculate all possible combining sequences of graphemes e.g. face followed by colour


Line 636: Line 710:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.textlen()</td><td>Count the number of Unicode code points in a source string.</p>
<tr><td>var=</td><td>strvar.textlen()</td><td><p>Count the number of Unicode code points in a source string.
</p>
<em>Returns:</em> A number.
<em>Returns:</em> A number.


Line 644: Line 719:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.fcount(sepstr)</td><td>Count the number of fields in a source string.</p>
<tr><td>var=</td><td>strvar.fcount(sepstr)</td><td><p>Count the number of fields in a source string.
<em>sepstr:</em> The separator character or substr that delimits individual fields.</p>
</p>
<em>Returns:</em> The count of the number of fields</p>
<p><em>sepstr:</em> The separator character or substr that delimits individual fields.
</p>
<p><em>Returns:</em> The count of the number of fields
</p>
This is similar to "var.count(sepstr) + 1" but it returns 0 for an empty source string.
This is similar to "var.count(sepstr) + 1" but it returns 0 for an empty source string.


Line 654: Line 732:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.count(sepstr)</td><td>Count the number of occurrences of a given substr in a source string.</p>
<tr><td>var=</td><td>strvar.count(sepstr)</td><td><p>Count the number of occurrences of a given substr in a source string.
<em>substr:</em> The substr to count.</p>
</p>
<em>Returns:</em> The count of the number of sepstr found.</p>
<p><em>substr:</em> The substr to count.
</p>
<p><em>Returns:</em> The count of the number of sepstr found.
</p>
Overlapping substrings are not counted.
Overlapping substrings are not counted.


Line 664: Line 745:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.starts(prefix)</td><td>Checks if a source string starts with a given prefix (substr).</p>
<tr><td>if</td><td>strvar.starts(prefix)</td><td><p>Checks if a source string starts with a given prefix (substr).
<em>prefix:</em> The substr to check for.</p>
</p>
<em>Returns:</em> True if the source string starts with the given prefix.</p>
<p><em>prefix:</em> The substr to check for.
</p>
<p><em>Returns:</em> True if the source string starts with the given prefix.
</p>
<em>Returns:</em> False if prefix is "". DIFFERS from c++, javascript, python3. See contains() for more info.
<em>Returns:</em> False if prefix is "". DIFFERS from c++, javascript, python3. See contains() for more info.


Line 674: Line 758:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.ends(suffix)</td><td>Checks if a source string ends with a given suffix (substr).</p>
<tr><td>if</td><td>strvar.ends(suffix)</td><td><p>Checks if a source string ends with a given suffix (substr).
<em>suffix:</em> The substr to check for.</p>
</p>
<em>Returns:</em> True if the source string ends with given suffix.</p>
<p><em>suffix:</em> The substr to check for.
</p>
<p><em>Returns:</em> True if the source string ends with given suffix.
</p>
<em>Returns:</em> False if suffix is "". DIFFERS from c++, javascript, python3. See contains() for more info.
<em>Returns:</em> False if suffix is "". DIFFERS from c++, javascript, python3. See contains() for more info.


Line 684: Line 771:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.contains(substr)</td><td>Checks if a given substr exists in a source string.</p>
<tr><td>if</td><td>strvar.contains(substr)</td><td><p>Checks if a given substr exists in a source string.
<em>substr:</em> The substr to check for.</p>
</p>
<em>Returns:</em> True if the source string starts with, ends with or contains the given substr.</p>
<p><em>substr:</em> The substr to check for.
<em>Returns:</em> False if suffix is "". DIFFERS from c++, javascript, python3</p>
</p>
Human logic: "" is not equal to "x" therefore x does not contain "".</p>
<p><em>Returns:</em> True if the source string starts with, ends with or contains the given substr.
Human logic: Check each item (character) in the list for equality with what I am looking for and return success if any are equal.</p>
</p>
<p><em>Returns:</em> False if suffix is "". DIFFERS from c++, javascript, python3
</p>
<p>Human logic: "" is not equal to "x" therefore x does not contain "".
</p>
<p>Human logic: Check each item (character) in the list for equality with what I am looking for and return success if any are equal.
</p>
Programmer logic: Compare as many characters as are in the search string for presence in the list of characters and return success if there are no failures.
Programmer logic: Compare as many characters as are in the search string for presence in the list of characters and return success if there are no failures.


Line 697: Line 790:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.index(substr, startchar1 = 1)</td><td>Find a substr in a source string.</p>
<tr><td>var=</td><td>strvar.index(substr, startchar1 = 1)</td><td><p>Find a substr in a source string.
<em>substr:</em> The substr to search for.</p>
</p>
<em>startchar1:</em> The char position (1 based) to start the search at. The default is 1, the first char.</p>
<p><em>substr:</em> The substr to search for.
</p>
<p><em>startchar1:</em> The char position (1 based) to start the search at. The default is 1, the first char.
</p>
<em>Returns:</em> The char position (1 based) that the substr is found at or 0 if not present.
<em>Returns:</em> The char position (1 based) that the substr is found at or 0 if not present.


Line 707: Line 803:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.indexn(substr, occurrence)</td><td>Find the nth occurrence of a substr in a source string.</p>
<tr><td>var=</td><td>strvar.indexn(substr, occurrence)</td><td><p>Find the nth occurrence of a substr in a source string.
<em>substr:</em> The string to search for.</p>
</p>
<p><em>substr:</em> The string to search for.
</p>
<em>Returns:</em> char position (1 based) or 0 if not present.
<em>Returns:</em> char position (1 based) or 0 if not present.


Line 716: Line 814:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.indexr(substr, startchar1 = -1)</td><td>Find the position of substr working backwards from the end of the string towards the beginning.</p>
<tr><td>var=</td><td>strvar.indexr(substr, startchar1 = -1)</td><td><p>Find the position of substr working backwards from the end of the string towards the beginning.
<em>substr:</em> The string to search for.</p>
</p>
<em>Returns:</em> The char position of the substr if found, or 0 if not.</p>
<p><em>substr:</em> The string to search for.
</p>
<p><em>Returns:</em> The char position of the substr if found, or 0 if not.
</p>
<em>startchar1:</em> defaults to -1 meaning start searching from the last char. Positive start1char1 counts from the beginning of the source string and negative startchar1 counts backwards from the last char.
<em>startchar1:</em> defaults to -1 meaning start searching from the last char. Positive start1char1 counts from the beginning of the source string and negative startchar1 counts backwards from the last char.


Line 726: Line 827:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.match(regex_str, regex_options = "")</td><td>Finds all matches of a given regular expression.</p>
<tr><td>var=</td><td>strvar.match(regex_str, regex_options = "")</td><td><p>Finds all matches of a given regular expression.
<em>Returns:</em> Zero or more matching substrings separated by FMs. Any groups are in VMs.
</p>
<p><em>Returns:</em> Zero or more matching substrings separated by FMs. Any groups are in VMs.


<pre><code class='hljs-ncdecl language-javascript'>let v1 = "abc1abc2"_var.match("BC(\\d)", "i"); // "bc1]1^bc2]2"_var
<pre><code class='hljs-ncdecl language-javascript'>let v1 = "abc1abc2"_var.match("BC(\\d)", "i"); // "bc1]1^bc2]2"_var
Line 733: Line 835:
let v2 = match("abc1abc2", "BC(\\d)", "i");</code></pre>
let v2 = match("abc1abc2", "BC(\\d)", "i");</code></pre>


<em>regex_options:</em></p>
 
<pre></p>
l - Literal (any regex chars are treated as normal chars)</p>
i - Case insensitive</p>
p - ECMAScript/Perl (the default)</p>
b - Basic POSIX (same as sed)</p>
e - Extended POSIX</p>
a - awk</p>
g - grep</p>
eg - egrep or grep -E</p>
</p>
</p>
char ranges like a-z are locale sensitive if ECMAScript</p>
<p><em>regex_options:</em>
</p>
<p><pre>
</p>
<p>l - Literal (any regex chars are treated as normal chars)
</p>
<p>i - Case insensitive
</p>
<p>p - ECMAScript/Perl (the default)
</p>
<p>b - Basic POSIX (same as sed)
</p>
<p>e - Extended POSIX
</p>
<p>a - awk
</p>
<p>g - grep
</p>
<p>eg - egrep or grep -E
</p>
</p>
m - Multiline. Default in boost (and therefore exodus)</p>
 
s - Single line. Default in std::regex</p>
<p>char ranges like a-z are locale sensitive if ECMAScript
f - First only. Only for replace() (not match() or search())</p>
</p>
w - Wildcard glob style (e.g. *.cfg) not regex style. Only for match() and search(). Not replace().</p>
 
</pre></p>
<p>m - Multiline. Default in boost (and therefore exodus)
</td></tr>
</p>
<tr><td>var=</td><td>strvar.match(regex)</td><td>Ditto</td></tr>
<p>s - Single line. Default in std::regex
<tr><td>var=</td><td>strvar.search(regex_str, io startchar1, regex_options = "")</td><td>Search for the first match of a regular expression.</p>
</p>
<em>startchar1:</em> [in] char position to start the search from</p>
<p>f - First only. Only for replace() (not match() or search())
<em>startchar1:</em> [out] char position to start the next search from</p>
</p>
<em>Returns:</em> The 1st match like match()</p>
<p>w - Wildcard glob style (e.g. *.cfg) not regex style. Only for match() and search(). Not replace().
regex_options as for match()
</p>
<p></pre>
</p>
</td></tr>
<tr><td>var=</td><td>strvar.match(regex)</td><td>Ditto</td></tr>
<tr><td>var=</td><td>strvar.search(regex_str, io startchar1, regex_options = "")</td><td><p>Search for the first match of a regular expression.
</p>
<p><em>startchar1:</em> [in] char position to start the search from
</p>
<p><em>startchar1:</em> [out] char position to start the next search from
</p>
<p><em>Returns:</em> The 1st match like match()
</p>
regex_options as for match()


<pre><code class='hljs-ncdecl language-javascript'>var startchar1 = 1;
<pre><code class='hljs-ncdecl language-javascript'>var startchar1 = 1;
Line 769: Line 893:
<tr><td>var=</td><td>strvar.search(regex, io startchar1)</td><td>Ditto given a rex</td></tr>
<tr><td>var=</td><td>strvar.search(regex, io startchar1)</td><td>Ditto given a rex</td></tr>
<tr><td>var=</td><td>strvar.search(regex)</td><td>Ditto starting from first char.</td></tr>
<tr><td>var=</td><td>strvar.search(regex)</td><td>Ditto starting from first char.</td></tr>
<tr><td>var=</td><td>strvar.hash(std::uint64_t modulus = 0)</td><td>Get a hash of a source string.</p>
<tr><td>var=</td><td>strvar.hash(std::uint64_t modulus = 0)</td><td><p>Get a hash of a source string.
<em>modulus:</em> The result is limited to [0, modulus)</p>
</p>
<em>Returns:</em> A 64 bit signed integer.</p>
<p><em>modulus:</em> The result is limited to [0, modulus)
</p>
<p><em>Returns:</em> A 64 bit signed integer.
</p>
MurmurHash3 is used.
MurmurHash3 is used.


Line 798: Line 925:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.tcase()</td><td>Convert to title case.</p>
<tr><td>var=</td><td>strvar.tcase()</td><td><p>Convert to title case.
</p>
<em>Returns:</em> Original source string with the first letter of each word is capitalised.
<em>Returns:</em> Original source string with the first letter of each word is capitalised.


Line 806: Line 934:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.fcase()</td><td>Convert to folded case.</p>
<tr><td>var=</td><td>strvar.fcase()</td><td><p>Convert to folded case.
Returns the source string standardised in a way to enable consistent indexing and searching,</p>
</p>
Case folding is the process of converting text to a case independent representation.</p>
<p>Returns the source string standardised in a way to enable consistent indexing and searching,
<em>https:</em>//www.w3.org/International/wiki/Case_folding</p>
</p>
Accents can be significant. As in French cote, coté, côte and côté.</p>
<p>Case folding is the process of converting text to a case independent representation.
</p>
<p><em>https:</em>//www.w3.org/International/wiki/Case_folding
</p>
<p>Accents can be significant. As in French cote, coté, côte and côté.
</p>
Case folding is not locale-dependent.
Case folding is not locale-dependent.


Line 818: Line 951:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.normalize()</td><td>Replace Unicode character sequences with their standardised NFC form.</p>
<tr><td>var=</td><td>strvar.normalize()</td><td><p>Replace Unicode character sequences with their standardised NFC form.
Unicode normalization is the process of converting Unicode strings to a standard form, making them binary comparable and suitable for text processing and comparison. It is an important part of Unicode text processing.</p>
</p>
For example, Unicode character "é" can be represented by either a single Unicode character, which is Unicode Code Point (\u00E9" - Latin Small Letter E with Acute), or a combination of two Unicode code points i.e. the ASCII letter "e" and a combining acute accent (Unicode Code Point "\u0301"). Unicode NFC definition converts the pair of code points to the single code point.</p>
<p>Unicode normalization is the process of converting Unicode strings to a standard form, making them binary comparable and suitable for text processing and comparison. It is an important part of Unicode text processing.
</p>
<p>For example, Unicode character "é" can be represented by either a single Unicode character, which is Unicode Code Point (\u00E9" - Latin Small Letter E with Acute), or a combination of two Unicode code points i.e. the ASCII letter "e" and a combining acute accent (Unicode Code Point "\u0301"). Unicode NFC definition converts the pair of code points to the single code point.
</p>
Normalization is not locale-dependent.
Normalization is not locale-dependent.


Line 828: Line 964:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.invert()</td><td>Simple reversible disguising of string text.</p>
<tr><td>var=</td><td>strvar.invert()</td><td><p>Simple reversible disguising of string text.
It works by treating the string as UTF8 encoded Unicode code points and inverting the first 8 bits of their Unicode Code Points.</p>
</p>
<em>Returns:</em> A string.</p>
<p>It works by treating the string as UTF8 encoded Unicode code points and inverting the first 8 bits of their Unicode Code Points.
invert(invert()) returns to the original text.</p>
</p>
ASCII bytes become multibyte UTF-8 so string sizes increase.</p>
<p><em>Returns:</em> A string.
Inverted characters remain on their original Unicode Code Page but are jumbled up.</p>
</p>
<p>invert(invert()) returns to the original text.
</p>
<p>ASCII bytes become multibyte UTF-8 so string sizes increase.
</p>
<p>Inverted characters remain on their original Unicode Code Page but are jumbled up.
</p>
Non-existant Unicode Code Points may be created but UTF8 encoding remains valid.
Non-existant Unicode Code Points may be created but UTF8 encoding remains valid.


Line 841: Line 983:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.lower()</td><td>Reduce all types of field mark chars by one level.</p>
<tr><td>var=</td><td>strvar.lower()</td><td><p>Reduce all types of field mark chars by one level.
Convert all FM to VM, VM to SM etc.</p>
</p>
<em>Returns:</em> The converted string.</p>
<p>Convert all FM to VM, VM to SM etc.
Note that subtext ST chars are not converted because they are already the lowest level.</p>
</p>
<p><em>Returns:</em> The converted string.
</p>
<p>Note that subtext ST chars are not converted because they are already the lowest level.
</p>
String size remains identical.
String size remains identical.


Line 852: Line 998:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.raise()</td><td>Increase all types of field mark chars by one level.</p>
<tr><td>var=</td><td>strvar.raise()</td><td><p>Increase all types of field mark chars by one level.
Convert all VM to FM, SM to VM etc.</p>
</p>
<em>Returns:</em> The converted string.</p>
<p>Convert all VM to FM, SM to VM etc.
The record mark char RM is not converted because it is already the highest level.</p>
</p>
String size remains identical.
<p><em>Returns:</em> The converted string.
</p>
<p>The record mark char RM is not converted because it is already the highest level.
</p>
String size remains identical.


<pre><code class='hljs-ncdecl language-javascript'>let v1 = "a1]b2]c3"_var.raise(); // "a1^b2^c3"_var
<pre><code class='hljs-ncdecl language-javascript'>let v1 = "a1]b2]c3"_var.raise(); // "a1^b2^c3"_var
Line 891: Line 1,041:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.trim(trimchars = " ")</td><td>Remove all leading, trailing and excessive inner bytes.</p>
<tr><td>var=</td><td>strvar.trim(trimchars = " ")</td><td><p>Remove all leading, trailing and excessive inner bytes.
</p>
<em>trimchars:</em> The chars (bytes) to remove. The default is space.
<em>trimchars:</em> The chars (bytes) to remove. The default is space.


Line 920: Line 1,071:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.first()</td><td>Get the first char of a string.</p>
<tr><td>var=</td><td>strvar.first()</td><td><p>Get the first char of a string.
<em>Returns:</em> A char, or "" if empty.</p>
</p>
<p><em>Returns:</em> A char, or "" if empty.
</p>
Equivalent to var.substr(1,length) or var[1, length] in Pick OS
Equivalent to var.substr(1,length) or var[1, length] in Pick OS


Line 929: Line 1,082:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.last()</td><td>Get the last char of a string.</p>
<tr><td>var=</td><td>strvar.last()</td><td><p>Get the last char of a string.
<em>Returns:</em> A char, or "" if empty.</p>
</p>
<p><em>Returns:</em> A char, or "" if empty.
</p>
Equivalent to var.substr(-1, 1) or var[-1, 1] in Pick OS
Equivalent to var.substr(-1, 1) or var[-1, 1] in Pick OS


Line 938: Line 1,093:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.first(std::size_t length)</td><td>Get the first n chars of a source string.</p>
<tr><td>var=</td><td>strvar.first(std::size_t length)</td><td><p>Get the first n chars of a source string.
<em>length:</em> The number of chars (bytes) to get.</p>
</p>
<em>Returns:</em> A string of up to n chars.</p>
<p><em>length:</em> The number of chars (bytes) to get.
</p>
<p><em>Returns:</em> A string of up to n chars.
</p>
Equivalent to var.substr(1, length) or var[1, length] in Pick OS
Equivalent to var.substr(1, length) or var[1, length] in Pick OS


Line 948: Line 1,106:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.last(std::size_t length)</td><td>Extract up to length trailing chars</p>
<tr><td>var=</td><td>strvar.last(std::size_t length)</td><td><p>Extract up to length trailing chars
</p>
Equivalent to var.substr(-length, length) or var[-length, length] in Pick OS
Equivalent to var.substr(-length, length) or var[-length, length] in Pick OS


Line 956: Line 1,115:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.cut(length)</td><td>Remove n chars (bytes) from the source string.</p>
<tr><td>var=</td><td>strvar.cut(length)</td><td><p>Remove n chars (bytes) from the source string.
<em>length:</em> Positive to remove first n chars or negative to remove the last n chars.</p>
</p>
If the absolute value of length is >= the number of chars in the source string then all chars will be removed.</p>
<p><em>length:</em> Positive to remove first n chars or negative to remove the last n chars.
</p>
<p>If the absolute value of length is >= the number of chars in the source string then all chars will be removed.
</p>
Equivalent to var.substr(length) or var[1, length] = "" in Pick OS
Equivalent to var.substr(length) or var[1, length] = "" in Pick OS


Line 966: Line 1,128:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.paste(pos1, length, replacestr)</td><td>Insert a substr at an given position after removing a given number of chars.</p>
<tr><td>var=</td><td>strvar.paste(pos1, length, replacestr)</td><td><p>Insert a substr at an given position after removing a given number of chars.
</p>
 
<p><em>pos1:</em> 0 or 1 : Remove length chars from the beginning and insert at the beginning.
</p>
<p><em>pos1:</em> > than the length of the source string. Insert after the last char.
</p>
<p><em>pos1:</em> -1 : Remove up to length chars before inserting.Insert on or before the last char.
</p>
<p><em>pos1:</em> -2 : Insert on or before the penultimate char.
</p>
</p>
<em>pos1:</em> 0 or 1 : Remove length chars from the beginning and insert at the beginning.</p>
<em>pos1:</em> > than the length of the source string. Insert after the last char.</p>
<em>pos1:</em> -1 : Remove up to length chars before inserting.Insert on or before the last char.</p>
<em>pos1:</em> -2 : Insert on or before the penultimate char.</p>
Equivalent to var[pos1, length] = substr in Pick OS
Equivalent to var[pos1, length] = substr in Pick OS


Line 979: Line 1,146:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.paste(pos1, insertstr)</td><td>Insert text at char position without overwriting any following chars</p>
<tr><td>var=</td><td>strvar.paste(pos1, insertstr)</td><td><p>Insert text at char position without overwriting any following chars
</p>
Equivalent to var[pos1, 0] = substr in Pick OS
Equivalent to var[pos1, 0] = substr in Pick OS


Line 987: Line 1,155:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.prefix(insertstr)</td><td>Insert text at the beginning</p>
<tr><td>var=</td><td>strvar.prefix(insertstr)</td><td><p>Insert text at the beginning
</p>
Equivalent to var[0, 0] = substr in Pick OS
Equivalent to var[0, 0] = substr in Pick OS


Line 1,001: Line 1,170:
let v2 = append("abc", " is ", 10, " ok", '.');</code></pre>
let v2 = append("abc", " is ", 10, " ok", '.');</code></pre>
</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.pop()</td><td>Remove one trailing char.</p>
<tr><td>var=</td><td>strvar.pop()</td><td><p>Remove one trailing char.
</p>
Equivalent to var[-1, 1] = "" in Pick OS
Equivalent to var[-1, 1] = "" in Pick OS


Line 1,009: Line 1,179:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.field(delimiter, fieldnx = 1, nfieldsx = 1)</td><td>Copies one or more consecutive fields from a string given a delimiter</p>
<tr><td>var=</td><td>strvar.field(delimiter, fieldnx = 1, nfieldsx = 1)</td><td><p>Copies one or more consecutive fields from a string given a delimiter
<em>delimiter:</em> A Unicode character.</p>
</p>
<em>fieldno:</em> The first field is 1, the last field is -1.</p>
<p><em>delimiter:</em> A Unicode character.
</p>
<p><em>fieldno:</em> The first field is 1, the last field is -1.
</p>
<em>Returns:</em> A substring
<em>Returns:</em> A substring


Line 1,024: Line 1,197:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.fieldstore(separator, fieldno, nfields, replacement)</td><td>fieldstore() replaces, inserts or deletes subfields in a string.</p>
<tr><td>var=</td><td>strvar.fieldstore(separator, fieldno, nfields, replacement)</td><td><p>fieldstore() replaces, inserts or deletes subfields in a string.
<em>fieldno:</em> The field number to replace or, if not 1, the field number to start at. Negative fieldno counts backwards from the last field.</p>
<em>nfields:</em> The number of fields to replace or, if negative, the number of fields to delete first. Can be 0 to cause simple insertion of fields.</p>
<em>replacement:</em> A string that is the replacement field or fields.</p>
<em>Returns:</em> A modified copy of the original string.</p>
There is no way to simply delete n fields because the replacement argument cannot be omitted, however one can achieve the same result by replacing n+1 fields with the n+1th field.</p>
</p>
</p>
<p><em>fieldno:</em> The field number to replace or, if not 1, the field number to start at. Negative fieldno counts backwards from the last field.
</p>
<p><em>nfields:</em> The number of fields to replace or, if negative, the number of fields to delete first. Can be 0 to cause simple insertion of fields.
</p>
<p><em>replacement:</em> A string that is the replacement field or fields.
</p>
<p><em>Returns:</em> A modified copy of the original string.
</p>
<p>There is no way to simply delete n fields because the replacement argument cannot be omitted, however one can achieve the same result by replacing n+1 fields with the n+1th field.
</p>
The replacement can contain multiple fields itself. If replacing n fields and the replacement contains < n fields then the remaining fields become "". Conversely, if the replacement contains more fields than are required, they are discarded.
The replacement can contain multiple fields itself. If replacing n fields and the replacement contains < n fields then the remaining fields become "". Conversely, if the replacement contains more fields than are required, they are discarded.


Line 1,050: Line 1,229:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.substr(pos1, length)</td><td>substr version 1.</p>
<tr><td>var=</td><td>strvar.substr(pos1, length)</td><td><p>substr version 1.
Copies a substr of length chars from a given a starting char position.</p>
</p>
<em>Returns:</em> A substr or "".</p>
<p>Copies a substr of length chars from a given a starting char position.
<em>pos1:</em> The char position to start at. If negative then start from a position counting backwards from the last char</p>
</p>
<em>length:</em> The number of chars to copy. If negative then copy backwards. This reverses the order of the chars in the returned substr.</p>
<p><em>Returns:</em> A substr or "".
Equivalent to var[start, length] in Pick OS</p>
</p>
<p><em>pos1:</em> The char position to start at. If negative then start from a position counting backwards from the last char
</p>
<p><em>length:</em> The number of chars to copy. If negative then copy backwards. This reverses the order of the chars in the returned substr.
</p>
<p>Equivalent to var[start, length] in Pick OS
</p>
Not Unicode friendly.
Not Unicode friendly.


Line 1,076: Line 1,261:
</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.b(pos1, length)</td><td>Abbreviated alias of substr version 1.</td></tr>
<tr><td>var=</td><td>strvar.b(pos1, length)</td><td>Abbreviated alias of substr version 1.</td></tr>
<tr><td>var=</td><td>strvar.substr(pos1)</td><td>substr version 2.</p>
<tr><td>var=</td><td>strvar.substr(pos1)</td><td><p>substr version 2.
Copies a substr from a given char position up to the end of the source string</p>
</p>
<em>Returns:</em> A substr or "".</p>
<p>Copies a substr from a given char position up to the end of the source string
<em>pos1:</em> The char position to start at. If negative then start from a position counting backwards from the last char</p>
</p>
Equivalent to var[pos1, 9999999] in Pick OS</p>
<p><em>Returns:</em> A substr or "".
</p>
<p><em>pos1:</em> The char position to start at. If negative then start from a position counting backwards from the last char
</p>
<p>Equivalent to var[pos1, 9999999] in Pick OS
</p>
Partially Unicode friendly but pos1 is in chars.
Partially Unicode friendly but pos1 is in chars.


Line 1,089: Line 1,279:
</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.b(pos1)</td><td>Shorthand alias of substr version 2.</td></tr>
<tr><td>var=</td><td>strvar.b(pos1)</td><td>Shorthand alias of substr version 2.</td></tr>
<tr><td>var=</td><td>strvar.substr(pos1, delimiterchars, out pos2)</td><td>substr version 3.</p>
<tr><td>var=</td><td>strvar.substr(pos1, delimiterchars, out pos2)</td><td><p>substr version 3.
Copies a substr from a given char position up to (but excluding) any one of some given delimiter chars</p>
</p>
<em>Returns:</em> A substr or "".</p>
<p>Copies a substr from a given char position up to (but excluding) any one of some given delimiter chars
<em>pos1:</em> [in] The position of the first char to copy. Negative positions count backwards from the last char of the string.</p>
</p>
<em>pos2:</em> [out] The position of the next delimiter char, or one char position after the end of the source string if no subsequent delimiter chars are found.</p>
<p><em>Returns:</em> A substr or "".
<em>COL2:</em> is a predefined variable that can be used for pos2 instead of declaring a variable.</p>
</p>
An empty string may be returned if pos1 [in] points to one of the delimiter chars or points beyond the end of the source string.</p>
<p><em>pos1:</em> [in] The position of the first char to copy. Negative positions count backwards from the last char of the string.
Equivalent to var[pos1, ",."] in Pick OS (non-numeric length).</p>
</p>
Works with any encoding including UTF8 for the source string but the delimiter chars are bytes.</p>
<p><em>pos2:</em> [out] The position of the next delimiter char, or one char position after the end of the source string if no subsequent delimiter chars are found.
Add 1 to pos2 to skip over the next delimiter char to copy the next substr</p>
</p>
Works with any encoding including UTF8 for the source string but the delimiter chars are bytes.</p>
<p><em>COL2:</em> is a predefined variable that can be used for pos2 instead of declaring a variable.
</p>
<p>An empty string may be returned if pos1 [in] points to one of the delimiter chars or points beyond the end of the source string.
</p>
<p>Equivalent to var[pos1, ",."] in Pick OS (non-numeric length).
</p>
<p>Works with any encoding including UTF8 for the source string but the delimiter chars are bytes.
</p>
<p>Add 1 to pos2 to skip over the next delimiter char to copy the next substr
</p>
<p>Works with any encoding including UTF8 for the source string but the delimiter chars are bytes.
</p>
This function is similar to std::string::find_first_of but that function only returns pos2.
This function is similar to std::string::find_first_of but that function only returns pos2.


Line 1,109: Line 1,310:
</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.b(pos1, delimiterchars, out pos2)</td><td>Shorthand alias of substr version 3.</td></tr>
<tr><td>var=</td><td>strvar.b(pos1, delimiterchars, out pos2)</td><td>Shorthand alias of substr version 3.</td></tr>
<tr><td>var=</td><td>strvar.substr2(io pos1, out delimiterno)</td><td>substr version 4.</p>
<tr><td>var=</td><td>strvar.substr2(io pos1, out delimiterno)</td><td><p>substr version 4.
Copies a substr from a given char position up to (but excluding) the next field mark char (RM, FM, VM, SM, TM, ST).</p>
</p>
<em>Returns:</em> A substr or "".</p>
<p>Copies a substr from a given char position up to (but excluding) the next field mark char (RM, FM, VM, SM, TM, ST).
<em>pos1:</em> [in] The position of the first char to copy. Negative positions count backwards from the last char of the string.</p>
</p>
<em>pos1:</em> [out] The position of the first char of the next substr after whatever field mark char is found, or one char position after the end of the source string if no subsequent field mark char is found.</p>
<p><em>Returns:</em> A substr or "".
<em>field_mark_no:</em> [out] A number (1-6) indicating which of the standard field mark chars was found, or 0 if not.</p>
</p>
An empty string may be returned if the pos1 [in] points to one of the field marks or beyond the end of the source string.</p>
<p><em>pos1:</em> [in] The position of the first char to copy. Negative positions count backwards from the last char of the string.
pos1 [out] is correctly positioned to copy the next substr.</p>
</p>
Works with any encoding including UTF8. Was called "remove" in Pick OS.</p>
<p><em>pos1:</em> [out] The position of the first char of the next substr after whatever field mark char is found, or one char position after the end of the source string if no subsequent field mark char is found.
The equivalent in Pick OS was the statement "Remove variable From string At column Setting flag"</p>
</p>
...</p>
<p><em>field_mark_no:</em> [out] A number (1-6) indicating which of the standard field mark chars was found, or 0 if not.
This function is valuable for high performance processing of dynamic arrays.</p>
</p>
It is notably used in "list" to print parallel columns of mixed combinations of multivalues/subvalues and text marks correctly lined up mv to mv, sv to sv, tm to tm even when particular values, subvalues and text fragments are missing from particular columns.</p>
<p>An empty string may be returned if the pos1 [in] points to one of the field marks or beyond the end of the source string.
</p>
<p>pos1 [out] is correctly positioned to copy the next substr.
</p>
<p>Works with any encoding including UTF8. Was called "remove" in Pick OS.
</p>
<p>The equivalent in Pick OS was the statement "Remove variable From string At column Setting flag"
</p>
<p>...
</p>
<p>This function is valuable for high performance processing of dynamic arrays.
</p>
<p>It is notably used in "list" to print parallel columns of mixed combinations of multivalues/subvalues and text marks correctly lined up mv to mv, sv to sv, tm to tm even when particular values, subvalues and text fragments are missing from particular columns.
</p>
It is similar to version 3 of substr - substr(pos1, delimiterchars, pos2) except that in this version the delimiter chars are hard coded as the standard field mark chars (RM, FM, VM, SM, TM, ST) and it returns the first char position of the next substr, not the char position of the next field mark char.
It is similar to version 3 of substr - substr(pos1, delimiterchars, pos2) except that in this version the delimiter chars are hard coded as the standard field mark chars (RM, FM, VM, SM, TM, ST) and it returns the first char position of the next substr, not the char position of the next field mark char.


Line 1,131: Line 1,345:
</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.b2(io pos1, out field_mark_no)</td><td>Shorthand alias of substr version 4.</td></tr>
<tr><td>var=</td><td>strvar.b2(io pos1, out field_mark_no)</td><td>Shorthand alias of substr version 4.</td></tr>
<tr><td>var=</td><td>strvar.convert(fromchars, tochars)</td><td>Convert or delete chars one for one to other chars</p>
<tr><td>var=</td><td>strvar.convert(fromchars, tochars)</td><td><p>Convert or delete chars one for one to other chars
<em>from_chars:</em> chars to convert. If longer than to_chars then delete those characters instead of converting them.</p>
</p>
<em>to_chars:</em> chars to convert to</p>
<p><em>from_chars:</em> chars to convert. If longer than to_chars then delete those characters instead of converting them.
</p>
<p><em>to_chars:</em> chars to convert to
</p>
Not UTF8 compatible.
Not UTF8 compatible.


Line 1,148: Line 1,365:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.replace(fromstr, tostr)</td><td>Replace all occurrences of one substr with another.</p>
<tr><td>var=</td><td>strvar.replace(fromstr, tostr)</td><td><p>Replace all occurrences of one substr with another.
</p>
Case sensitive.
Case sensitive.


Line 1,156: Line 1,374:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.replace(regex, tostr)</td><td>Replace substring(s) using a regular expression.</p>
<tr><td>var=</td><td>strvar.replace(regex, replacement_str)</td><td><p>Replace substrings using a regular expression.
Use $0, $1, $2 in tostr to refer to groups defined in the regex.
</p>
 
<p><em>regex:</em> A regular expression created by rex() or _rex.
<pre><code class='hljs-ncdecl language-javascript'>let v1 = "A a B b"_var.replace("[A-Z]"_rex, "'$0'"); // "'A' a 'B' b"
</p>
// or
<p><em>replacement_str:</em> A literal to replace all matched substrings.
</p>
<p>The replacement string can include the following special replacement patterns:
</p>
<p>Pattern  Inserts
</p>
<p>$$      Inserts a "$".
</p>
<p>$&      Inserts the matched substring. Equivalent to $0.
</p>
<p>$`      Inserts the portion of the string that precedes the matched substring.
</p>
<p>$'      Inserts the portion of the string that follows the matched substring.
</p>
$n      Inserts the nth (1-indexed) capturing group where n is a positive integer less than 100.
 
<pre><code class='hljs-ncdecl language-javascript'>let v1 = "A a B b"_var.replace("[A-Z]"_rex, "'$0'"); // "'A' a 'B' b"
// or
let v2 = replace("A a B b", "[A-Z]"_rex, "'$0'");</code></pre>
let v2 = replace("A a B b", "[A-Z]"_rex, "'$0'");</code></pre>
</td></tr>
<tr><td>var=</td><td>strvar.replace(regex, SomeFunction(match_str))</td><td><p>Replace substrings using a regular expression and a custom function.
</p>
<p>Allows very complex string conversions.
</p>
<p><em>SomeFunction:</em> Must return a var. Can be an inline anonymous lambda function.
</p>
<p>e.g. [](auto match_str) {return match_str;} // Does nothing.
</p>
<em>match_str:</em> Text of a single match. If regex groups are used, match_str.f(1, 1) is the whole match, match_str.f(1, 2) is the first group, etc.
<pre><code class='hljs-ncdecl language-javascript'>// Decode hex escape codes.
var v1 = R"(--\0x3B--\0x2F--)";                                // Hex escape codes.
v1.replacer(
    R"(\\0x[0-9a-fA-F]{2,2})"_rex,                              // Finds \0xFF.
    [](auto match_str) {return match_str.cut(3).iconv("HEX");}  // Decodes to a char.
);
assert(v1 == "--;--/--");
// Reformat dates using groups.
var v2 = "Date: 03-15-2025";
v2.replacer(
    R"((\d{2})-(\d{2})-(\d{4}))"_rex,
    [](auto match_str) {return match_str.f(1, 4) ^ "-" ^ match_str.f(1, 2) ^ "-" ^ match_str.f(1, 3);}
);
assert(v2 == "Date: 2025-03-15");</code></pre>


</td></tr>
</td></tr>
Line 1,171: Line 1,433:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.sort(delimiter = FM)</td><td>Reorder fields in an FM or VM etc. separated list in ascending order</p>
<tr><td>var=</td><td>strvar.sort(delimiter = FM)</td><td><p>Reorder fields in an FM or VM etc. separated list in ascending order
</p>
Numeric data:
Numeric data:


Line 1,199: Line 1,462:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.parse(char sepchar = ' ')</td><td>Split a delimited string with embedded quotes into a dynamic array.</p>
<tr><td>var=</td><td>strvar.parse(char sepchar = ' ')</td><td><p>Split a delimited string with embedded quotes into a dynamic array.
Can be used to process CSV data.</p>
</p>
<p>Can be used to process CSV data.
</p>
Replaces separator chars with FM chars except inside double or single quotes and ignoring escaped quotes &bsol;" &bsol;'
Replaces separator chars with FM chars except inside double or single quotes and ignoring escaped quotes &bsol;" &bsol;'


Line 1,208: Line 1,473:


</td></tr>
</td></tr>
<tr><td>dim=</td><td>strvar.split(delimiter = FM)</td><td>Split a delimited string into a dim array.</p>
<tr><td>dim=</td><td>strvar.split(delimiter = FM)</td><td><p>Split a delimited string into a dim array.
The delimiter can be multibyte Unicode.</p>
</p>
<p>The delimiter can be multibyte Unicode.
</p>
<em>Returns:</em> A dim array.
<em>Returns:</em> A dim array.


Line 1,223: Line 1,490:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td></td><td>strvar.ucaser()</td><td>Upper case</p>
<tr><td></td><td>strvar.ucaser()</td><td><p>Upper case
</p>
All string mutators follow the same pattern as ucaser.<br>See the non-mutating functions for details.
All string mutators follow the same pattern as ucaser.<br>See the non-mutating functions for details.


Line 1,263: Line 1,531:
<tr><td></td><td>strvar.textconverter(from_characters, to_characters)</td><td></td></tr>
<tr><td></td><td>strvar.textconverter(from_characters, to_characters)</td><td></td></tr>
<tr><td></td><td>strvar.replacer(regex, tostr)</td><td></td></tr>
<tr><td></td><td>strvar.replacer(regex, tostr)</td><td></td></tr>
<tr><td></td><td>strvar.replacer(regex, SomeFunction(match_str))</td><td></td></tr>
<tr><td></td><td>strvar.replacer(fromstr, tostr)</td><td></td></tr>
<tr><td></td><td>strvar.replacer(fromstr, tostr)</td><td></td></tr>
<tr><td></td><td>strvar.uniquer()</td><td></td></tr>
<tr><td></td><td>strvar.uniquer()</td><td></td></tr>
Line 1,274: Line 1,543:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>var.oconv(convstr)</td><td>Converts internal data to output external display format according to a given conversion code or pattern</p>
<tr><td>var=</td><td>var.oconv(convstr)</td><td><p>Converts internal data to output external display format according to a given conversion code or pattern
If the internal data is invalid and cannot be converted then most conversions return the ORIGINAL data unconverted</p>
</p>
Throws a runtime error VarNotImplemented if convstr is invalid</p>
<p>If the internal data is invalid and cannot be converted then most conversions return the ORIGINAL data unconverted
</p>
<p>Throws a runtime error VarNotImplemented if convstr is invalid
</p>
See [[#ICONV/OCONV PATTERNS]]
See [[#ICONV/OCONV PATTERNS]]


Line 1,284: Line 1,556:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var.iconv(convstr)</td><td>Converts external data to internal format according to a given conversion code or pattern</p>
<tr><td>var=</td><td>var.iconv(convstr)</td><td><p>Converts external data to internal format according to a given conversion code or pattern
If the external data is invalid and cannot be converted then most conversions return the EMPTY STRING ""</p>
</p>
Throws a runtime error VarNotImplemented if convstr is invalid</p>
<p>If the external data is invalid and cannot be converted then most conversions return the EMPTY STRING ""
</p>
<p>Throws a runtime error VarNotImplemented if convstr is invalid
</p>
See [[#ICONV/OCONV PATTERNS]]
See [[#ICONV/OCONV PATTERNS]]


Line 1,294: Line 1,569:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var.format(fmt_str, args, ...)</td><td>Classic format function in printf style</p>
<tr><td>var=</td><td>var.format(fmt_str, args, ...)</td><td><p>Classic format function in printf style
vars can be formatted either with C++ format codes e.g. {:_>8.2f}</p>
</p>
<p>vars can be formatted either with C++ format codes e.g. {:_>8.2f}
</p>
or with exodus oconv codes e.g. {::MD20P|R(_)#8} as in the below example.
or with exodus oconv codes e.g. {::MD20P|R(_)#8} as in the below example.


Line 1,305: Line 1,582:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.from_codepage(codepage)</td><td>Converts from codepage encoded text to UTF-8 encoded exodus text</p>
<tr><td>var=</td><td>strvar.from_codepage(codepage)</td><td><p>Converts from codepage encoded text to UTF-8 encoded exodus text
e.g. Codepage "CP1124" (Ukrainian).</p>
</p>
<p>e.g. Codepage "CP1124" (Ukrainian).
</p>
Use Linux command "iconv -l" for complete list of code pages and encodings.
Use Linux command "iconv -l" for complete list of code pages and encodings.


Line 1,327: Line 1,606:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>strvar.f(fieldno, valueno = 0, subvalueno = 0)</td><td>f() is a highly abbreviated alias for the Pick OS field/value/subvalue extract() function.</p>
<tr><td>var=</td><td>strvar.f(fieldno, valueno = 0, subvalueno = 0)</td><td><p>f() is a highly abbreviated alias for the Pick OS field/value/subvalue extract() function.
"f()" can be thought of as "field" although the function can extract values and subvalues as well.</p>
</p>
The convenient Pick OS angle bracket syntax for field extraction (e.g. xxx<20>) is not available in C++.</p>
<p>"f()" can be thought of as "field" although the function can extract values and subvalues as well.
</p>
<p>The convenient Pick OS angle bracket syntax for field extraction (e.g. xxx<20>) is not available in C++.
</p>
The abbreviated exodus field extraction function (e.g. xxx.f(20)) is provided instead since field access is extremely heavily used in source code.
The abbreviated exodus field extraction function (e.g. xxx.f(20)) is provided instead since field access is extremely heavily used in source code.


Line 1,345: Line 1,627:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.update(fieldno, valueno, subvalueno, replacement)</td><td>Same as var.updater() function but returns a new string instead of updating a variable in place.<br>Rarely used.</p>
<tr><td>var=</td><td>strvar.update(fieldno, valueno, subvalueno, replacement)</td><td><p>Same as var.updater() function but returns a new string instead of updating a variable in place.<br>Rarely used.
</p>
"update()" was called "replace()" in Pick OS/Basic.</td></tr>
"update()" was called "replace()" in Pick OS/Basic.</td></tr>
<tr><td>var=</td><td>strvar.update(fieldno, valueno, replacement)</td><td>Ditto for a specific multivalue</td></tr>
<tr><td>var=</td><td>strvar.update(fieldno, valueno, replacement)</td><td>Ditto for a specific multivalue</td></tr>
Line 1,352: Line 1,635:
<tr><td>var=</td><td>strvar.insert(fieldno, valueno, insertion)</td><td>Ditto for a specific multivalue</td></tr>
<tr><td>var=</td><td>strvar.insert(fieldno, valueno, insertion)</td><td>Ditto for a specific multivalue</td></tr>
<tr><td>var=</td><td>strvar.insert(fieldno, insertion)</td><td>Ditto for a specific field</td></tr>
<tr><td>var=</td><td>strvar.insert(fieldno, insertion)</td><td>Ditto for a specific field</td></tr>
<tr><td>var=</td><td>strvar.remove(fieldno, valueno = 0, subvalueno = 0)</td><td>Same as var.remover() function but returns a new string instead of updating a variable in place.</p>
<tr><td>var=</td><td>strvar.remove(fieldno, valueno = 0, subvalueno = 0)</td><td><p>Same as var.remover() function but returns a new string instead of updating a variable in place.
</p>
"remove()" was called "delete()" in Pick OS/Basic.</td></tr>
"remove()" was called "delete()" in Pick OS/Basic.</td></tr>
</table>
</table>
Line 1,457: Line 1,741:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>strvar.locate(target)</td><td>locate() with only the target substr argument provided searches unordered values separated by any of the field mark chars.</p>
<tr><td>var=</td><td>strvar.locate(target)</td><td><p>locate() with only the target substr argument provided searches unordered values separated by any of the field mark chars.
<em>Returns:</em> The field, value, subvalue etc. number if found or 0 if not.</p>
</p>
<p><em>Returns:</em> The field, value, subvalue etc. number if found or 0 if not.
</p>
Searching for empty fields, values etc. (i.e. "") will work. Locating "" in "]yy" will return 1, in "xx]]zz" 2, and in "xx]yy]" 3, however, locating "" in "xx" will return 0 because there is conceptually no empty value in "xx". Locate "" in "" will return 1.
Searching for empty fields, values etc. (i.e. "") will work. Locating "" in "]yy" will return 1, in "xx]]zz" 2, and in "xx]yy]" 3, however, locating "" in "xx" will return 0 because there is conceptually no empty value in "xx". Locate "" in "" will return 1.


Line 1,466: Line 1,752:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.locate(target, out valueno)</td><td>locate() with only the target substr provided and setting returned searches unordered values separated by any type of field mark chars.</p>
<tr><td>if</td><td>strvar.locate(target, out valueno)</td><td><p>locate() with only the target substr provided and setting returned searches unordered values separated by any type of field mark chars.
<em>Returns:</em> True if found</p>
</p>
<p><em>Returns:</em> True if found
</p>
<em>Setting:</em> Field, value, subvalue etc. number if found or the max number + 1 if not. Suitable for additiom of new values
<em>Setting:</em> Field, value, subvalue etc. number if found or the max number + 1 if not. Suitable for additiom of new values


Line 1,476: Line 1,764:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.locate(target, out setting, fieldno, valueno = 0)</td><td>locate() the target in unordered fields if fieldno is 0, or values if a fieldno is specified, or subvalues if the valueno argument is provided.</p>
<tr><td>if</td><td>strvar.locate(target, out setting, fieldno, valueno = 0)</td><td><p>locate() the target in unordered fields if fieldno is 0, or values if a fieldno is specified, or subvalues if the valueno argument is provided.
<em>Returns:</em> True if found and with the field, value or subvalue number in setting.</p>
</p>
<p><em>Returns:</em> True if found and with the field, value or subvalue number in setting.
</p>
<em>Returns:</em> False if not found and with the max field, value or subvalue number found + 1 in setting. Suitable for replacement of new fields, values or subvalues.
<em>Returns:</em> False if not found and with the max field, value or subvalue number found + 1 in setting. Suitable for replacement of new fields, values or subvalues.


Line 1,484: Line 1,774:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.locateby(ordercode, target, out valueno)</td><td>locateby() without fieldno or valueno arguments searches ordered values separated by VM chars.</p>
<tr><td>if</td><td>strvar.locateby(ordercode, target, out valueno)</td><td><p>locateby() without fieldno or valueno arguments searches ordered values separated by VM chars.
The order code can be AL, DL, AR, DR meaning Ascending Left, Descending Right, Ascending Right, Ascending Left.</p>
</p>
Left is used to indicate alphabetic order where 10 < 2.</p>
<p>The order code can be AL, DL, AR, DR meaning Ascending Left, Descending Right, Ascending Right, Ascending Left.
Right is used to indicate numeric order where 10 > 2.</p>
</p>
Data must be in the correct order for searching to work properly.</p>
<p>Left is used to indicate alphabetic order where 10 < 2.
<em>Returns:</em> True if found.</p>
</p>
<p>Right is used to indicate numeric order where 10 > 2.
</p>
<p>Data must be in the correct order for searching to work properly.
</p>
<p><em>Returns:</em> True if found.
</p>
In case the target is not exactly found then the correct value no for inserting the target is returned in setting.
In case the target is not exactly found then the correct value no for inserting the target is returned in setting.


Line 1,506: Line 1,802:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.locateusing(usingchar, target, out setting, fieldno = 0, valueno = 0, subvalueno = 0)</td><td>locate() the target in a specific field, value or subvalue using a specified delimiter and unordered data</p>
<tr><td>if</td><td>strvar.locateusing(usingchar, target, out setting, fieldno = 0, valueno = 0, subvalueno = 0)</td><td><p>locate() the target in a specific field, value or subvalue using a specified delimiter and unordered data
<em>Returns:</em> True If found and returns in setting the number of the delimited field found.</p>
</p>
<em>Returns:</em> False if not found and returns in setting the maximum number of delimited fields + 1 if not found.</p>
<p><em>Returns:</em> True If found and returns in setting the number of the delimited field found.
</p>
<p><em>Returns:</em> False if not found and returns in setting the maximum number of delimited fields + 1 if not found.
</p>
This is similar to the main locate command but the delimiter char can be specified e.g. a comma or TM etc.
This is similar to the main locate command but the delimiter char can be specified e.g. a comma or TM etc.


Line 1,515: Line 1,814:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.locatebyusing(ordercode, usingchar, target, out setting, fieldno = 0, valueno = 0, subvalueno = 0)</td><td>locatebyusing() supports all the above features in a single function.</p>
<tr><td>if</td><td>strvar.locatebyusing(ordercode, usingchar, target, out setting, fieldno = 0, valueno = 0, subvalueno = 0)</td><td><p>locatebyusing() supports all the above features in a single function.
</p>
<em>Returns:</em> True if found.</td></tr>
<em>Returns:</em> True if found.</td></tr>
</table>
</table>
Line 1,522: Line 1,822:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>conn.connect(conninfo = "")</td><td>For all db operations, the operative var can either be a db connection created with dbconnect() or be any var and a default connection will be established on the fly.</p>
<tr><td>if</td><td>conn.connect(conninfo = "")</td><td><p>For all db operations, the operative var can either be a db connection created with dbconnect() or be any var and a default connection will be established on the fly.
The db connection string (conninfo) parameters are merged from the following places in descending priority.</p>
</p>
1. Provided in connect()'s conninfo argument. See 4. for the complete list of parameters.</p>
<p>The db connection string (conninfo) parameters are merged from the following places in descending priority.
2. Any environment variables EXO_HOST EXO_PORT EXO_USER EXO_DATA EXO_PASS EXO_TIME</p>
</p>
3. Any parameters found in a configuration file at ~/.config/exodus/exodus.cfg</p>
<p>1. Provided in connect()'s conninfo argument. See 4. for the complete list of parameters.
4. The default conninfo is "host=127.0.0.1 port=5432 dbname=exodus user=exodus password=somesillysecret connect_timeout=10"</p>
</p>
<p>2. Any environment variables EXO_HOST EXO_PORT EXO_USER EXO_DATA EXO_PASS EXO_TIME
</p>
<p>3. Any parameters found in a configuration file at ~/.config/exodus/exodus.cfg
</p>
<p>4. The default conninfo is "host=127.0.0.1 port=5432 dbname=exodus user=exodus password=somesillysecret connect_timeout=10"
</p>
Setting environment variable EXO_DBTRACE=1 will cause tracing of db interface including SQL commands.
Setting environment variable EXO_DBTRACE=1 will cause tracing of db interface including SQL commands.


Line 1,538: Line 1,844:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn.attach(filenames)</td><td>"attach" causes the given filenames to be associated with a specific connection for the remainder of the session.</p>
<tr><td>if</td><td>conn.attach(filenames)</td><td><p>"attach" causes the given filenames to be associated with a specific connection for the remainder of the session.
It is not necessary to attach files before opening them.</p>
</p>
Attachments can changed by calling attach() or open() on a different connection or they can be removed by calling detach().</p>
<p>It is not necessary to attach files before opening them.
<em>var:</em> Defaults to the default connection.</p>
</p>
<em>filenames:</em> FM separated list.</p>
<p>Attachments can changed by calling attach() or open() on a different connection or they can be removed by calling detach().
<em>Returns:</em> false if any filename does not exist and cannot be opened on the given connection. All filenames that can be opened on the conneciton are attached even if some cannot.</p>
</p>
<p><em>var:</em> Defaults to the default connection.
</p>
<p><em>filenames:</em> FM separated list.
</p>
<p><em>Returns:</em> false if any filename does not exist and cannot be opened on the given connection. All filenames that can be opened on the conneciton are attached even if some cannot.
</p>
Internally, attach merely opens each filename on the given connection causing them to be added to an internal cache.
Internally, attach merely opens each filename on the given connection causing them to be added to an internal cache.


Line 1,552: Line 1,864:


</td></tr>
</td></tr>
<tr><td></td><td>conn.detach(filenames)</td><td>Removes files from the internal cache created by previous open() and attach() calls.</p>
<tr><td></td><td>conn.detach(filenames)</td><td><p>Removes files from the internal cache created by previous open() and attach() calls.
<em>var:</em> Defaults to the default connection.</p>
</p>
<em>filenames:</em> FM separated list.</p>
<p><em>var:</em> Defaults to the default connection.
</p>
<p><em>filenames:</em> FM separated list.
</p>
</td></tr>
</td></tr>
<tr><td>if</td><td>conn.begintrans()</td><td>Begin a db transaction.
<tr><td>if</td><td>conn.begintrans()</td><td>Begin a db transaction.
Line 1,577: Line 1,892:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn.committrans()</td><td>Commit a db transaction.</p>
<tr><td>if</td><td>conn.committrans()</td><td><p>Commit a db transaction.
</p>
<em>Returns:</em> True if successfully committed or if there was no transaction in progress, otherwise false.
<em>Returns:</em> True if successfully committed or if there was no transaction in progress, otherwise false.


Line 1,585: Line 1,901:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn.sqlexec(sqlcmd)</td><td>Execute an sql command.</p>
<tr><td>if</td><td>conn.sqlexec(sqlcmd)</td><td><p>Execute an sql command.
</p>
<em>Returns:</em> True if there was no sql error otherwise lasterror() returns a detailed error message.
<em>Returns:</em> True if there was no sql error otherwise lasterror() returns a detailed error message.


Line 1,593: Line 1,910:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn.sqlexec(sqlcmd, io response)</td><td>Execute an SQL command and capture the response.</p>
<tr><td>if</td><td>conn.sqlexec(sqlcmd, io response)</td><td><p>Execute an SQL command and capture the response.
<em>Returns:</em> True if there was no sql error otherwise response contains a detailed error message.</p>
</p>
<em>response:</em> Any rows and columns returned are separated by RM and FM respectively. The first row is the column names.</p>
<p><em>Returns:</em> True if there was no sql error otherwise response contains a detailed error message.
</p>
<p><em>response:</em> Any rows and columns returned are separated by RM and FM respectively. The first row is the column names.
</p>
<em>Recommended:</em> Don't use sql directly unless you must to manage or configure a database.
<em>Recommended:</em> Don't use sql directly unless you must to manage or configure a database.


Line 1,612: Line 1,932:


</td></tr>
</td></tr>
<tr><td></td><td>conn.disconnectall()</td><td>Closes all connections and frees process resources both locally and in the database server(s).</p>
<tr><td></td><td>conn.disconnectall()</td><td><p>Closes all connections and frees process resources both locally and in the database server(s).
</p>
All connections are closed automatically when a process terminates.
All connections are closed automatically when a process terminates.


Line 1,620: Line 1,941:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::lasterror()</td><td>Returns: The last os or db error message.
<tr><td>var=</td><td>var::lasterror()</td><td>
<em>Returns:</em> The last os or db error message.


<pre><code class='hljs-ncdecl language-javascript'>var v1 = var::lasterror();
<pre><code class='hljs-ncdecl language-javascript'>var v1 = var::lasterror();
Line 1,627: Line 1,949:


</td></tr>
</td></tr>
<tr><td></td><td>var::loglasterror(source = "")</td><td>Log the last os or db error message.</p>
<tr><td></td><td>var::loglasterror(source = "")</td><td><p>Log the last os or db error message.
<em>Output:</em> to stdlog</p>
</p>
<p><em>Output:</em> to stdlog
</p>
Prefixes the output with source if provided.
Prefixes the output with source if provided.


Line 1,641: Line 1,965:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>conn.dbcreate(new_dbname, old_dbname = "")</td><td>Create a named database on a particular connection.</p>
<tr><td>if</td><td>conn.dbcreate(new_dbname, old_dbname = "")</td><td><p>Create a named database on a particular connection.
The target database cannot already exist.</p>
</p>
<p>The target database cannot already exist.
</p>
Optionally copies an existing database from the same connection and which cannot have any current connections.
Optionally copies an existing database from the same connection and which cannot have any current connections.


Line 1,652: Line 1,978:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn.dbcopy(from_dbname, to_dbname)</td><td>Create a named database as a copy of an existing database.</p>
<tr><td>if</td><td>conn.dbcopy(from_dbname, to_dbname)</td><td><p>Create a named database as a copy of an existing database.
The target database cannot already exist.</p>
</p>
<p>The target database cannot already exist.
</p>
The source database must exist on the same connection and cannot have any current connections.
The source database must exist on the same connection and cannot have any current connections.


Line 1,663: Line 1,991:


</td></tr>
</td></tr>
<tr><td>var=</td><td>conn.dblist()</td><td>Returns: A list of available databases on a particular connection.
<tr><td>var=</td><td>conn.dblist()</td><td>
<em>Returns:</em> A list of available databases on a particular connection.


<pre><code class='hljs-ncdecl language-javascript'>let v1 = conn.dblist();
<pre><code class='hljs-ncdecl language-javascript'>let v1 = conn.dblist();
Line 1,670: Line 1,999:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn.dbdelete(dbname)</td><td>Delete (drop) a named database.</p>
<tr><td>if</td><td>conn.dbdelete(dbname)</td><td><p>Delete (drop) a named database.
</p>
The target database must exist and cannot have any current connections.
The target database must exist and cannot have any current connections.


Line 1,679: Line 2,009:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn.createfile(filename)</td><td>Create a named db file.</p>
<tr><td>if</td><td>conn.createfile(filename)</td><td><p>Create a named db file.
</p>
filenames ending with "_temp" only last until the connection is closed.
filenames ending with "_temp" only last until the connection is closed.


Line 1,696: Line 2,027:


</td></tr>
</td></tr>
<tr><td>var=</td><td>conn.listfiles()</td><td>Returns: A list of all files in a database
<tr><td>var=</td><td>conn.listfiles()</td><td>
<em>Returns:</em> A list of all files in a database


<pre><code class='hljs-ncdecl language-javascript'>var conn = "exodus";
<pre><code class='hljs-ncdecl language-javascript'>var conn = "exodus";
Line 1,720: Line 2,052:


</td></tr>
</td></tr>
<tr><td>var=</td><td>conn_or_file.reccount(filename = "")</td><td>Returns: The approx. number of records in a db file.</p>
<tr><td>var=</td><td>conn_or_file.reccount(filename = "")</td><td>
Might return -1 if not known.</p>
<p><em>Returns:</em> The approx. number of records in a db file.
</p>
<p>Might return -1 if not known.
</p>
Not very accurate inside transactions.
Not very accurate inside transactions.


Line 1,730: Line 2,065:


</td></tr>
</td></tr>
<tr><td>if</td><td>conn_or_file.flushindex(filename = "")</td><td>Calls db maintenance function for a file or all files.</p>
<tr><td>if</td><td>conn_or_file.flushindex(filename = "")</td><td><p>Calls db maintenance function for a file or all files.
This doesnt actually flush any indexes but does make sure that reccount() function is reasonably accurate.</p>
</p>
<p>This doesnt actually flush any indexes but does make sure that reccount() function is reasonably accurate.
</p>
<em>Returns:</em> True if successful otherwise false if not and with lasterror() set.</td></tr>
<em>Returns:</em> True if successful otherwise false if not and with lasterror() set.</td></tr>
</table>
</table>
Line 1,738: Line 2,075:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>file.open(dbfilename, connection = "")</td><td>Opens a db file to a var which can be used in subsequent db function calls to access a specific file using a specific connection.</p>
<tr><td>if</td><td>file.open(dbfilename, connection = "")</td><td><p>Opens a db file to a var which can be used in subsequent db function calls to access a specific file using a specific connection.
<em>connection:</em> If not specified and the filename is present in an internal cache of filenames and connections created by previous calls to open() or attach() then open() returns true. If it is not present in the cache then the default connection will be checked.</p>
</p>
<p><em>connection:</em> If not specified and the filename is present in an internal cache of filenames and connections created by previous calls to open() or attach() then open() returns true. If it is not present in the cache then the default connection will be checked.
</p>
<em>Returns:</em> True if the filename was present in the cache OR if the db connection reports that the file is present.
<em>Returns:</em> True if the filename was present in the cache OR if the db connection reports that the file is present.


Line 1,748: Line 2,087:


</td></tr>
</td></tr>
<tr><td></td><td>file.close()</td><td>Closes db file var</p>
<tr><td></td><td>file.close()</td><td><p>Closes db file var
</p>
Does nothing currently since database file vars consume no resources
Does nothing currently since database file vars consume no resources


Line 1,757: Line 2,097:


</td></tr>
</td></tr>
<tr><td>if</td><td>file.createindex(fieldname, dictfile = "")</td><td>Creates a secondary index for a given db file and field name.</p>
<tr><td>if</td><td>file.createindex(fieldname, dictfile = "")</td><td><p>Creates a secondary index for a given db file and field name.
The fieldname must exist in a dictionary file. The default dictionary is "dict." ^ filename.</p>
</p>
<em>Returns:</em> False if the index cannot be created for any reason.</p>
<p>The fieldname must exist in a dictionary file. The default dictionary is "dict." ^ filename.
* Index already exists</p>
</p>
* File does not exist</p>
<p><em>Returns:</em> False if the index cannot be created for any reason.
* The dictionary file does not have a record with a key of the given field name.</p>
</p>
* The dictionary file does not exist. Default is "dict." ^ filename.</p>
<p>* Index already exists
</p>
<p>* File does not exist
</p>
<p>* The dictionary file does not have a record with a key of the given field name.
</p>
<p>* The dictionary file does not exist. Default is "dict." ^ filename.
</p>
* The dictionary field defines a calculated field that uses an exodus function. Using a psql function is OK.
* The dictionary field defines a calculated field that uses an exodus function. Using a psql function is OK.


Line 1,773: Line 2,120:


</td></tr>
</td></tr>
<tr><td>var=</td><td>file|conn.listindex(file_or_filename = "", fieldname = "")</td><td>Lists secondary indexes in a database or for a db file</p>
<tr><td>var=</td><td>file|conn.listindex(file_or_filename = "", fieldname = "")</td><td><p>Lists secondary indexes in a database or for a db file
</p>
<em>Returns:</em> False if the db file or fieldname are given and do not exist
<em>Returns:</em> False if the db file or fieldname are given and do not exist


Line 1,782: Line 2,130:


</td></tr>
</td></tr>
<tr><td>if</td><td>file.deleteindex(fieldname)</td><td>Deletes a secondary index for a db file and field name.</p>
<tr><td>if</td><td>file.deleteindex(fieldname)</td><td><p>Deletes a secondary index for a db file and field name.
<em>Returns:</em> False if the index cannot be deleted for any reason</p>
</p>
* File does not exist</p>
<p><em>Returns:</em> False if the index cannot be deleted for any reason
</p>
<p>* File does not exist
</p>
* Index does not already exists
* Index does not already exists


Line 1,793: Line 2,144:


</td></tr>
</td></tr>
<tr><td>var=</td><td>file.lock(key)</td><td>Places a metaphorical db lock on a particular record given a db file and key.</p>
<tr><td>var=</td><td>file.lock(key)</td><td><p>Places a metaphorical db lock on a particular record given a db file and key.
This is a advisory lock, not a physical lock, since it makes no restriction on the access or modification of data by other connections.</p>
</p>
Neither the db file nor the record key need to actually exist since a lock is just a hash of the db file name and key combined.</p>
<p>This is a advisory lock, not a physical lock, since it makes no restriction on the access or modification of data by other connections.
If another connection attempts to place an identical lock on the same database it will be denied.</p>
</p>
Locks can be removed by unlock() or unlockall() or will be automatically removed at the end of a transaction or when the connection is closed.</p>
<p>Neither the db file nor the record key need to actually exist since a lock is just a hash of the db file name and key combined.
If the same process attempts to place an identical lock more than once it may be denied (if not in a transaction) or succeed but be ignored (if in a transaction).</p>
</p>
Locks can be used to avoid processing a transaction simultaneously with another connection only to have one of them fail due to mutually updating the same records.</p>
<p>If another connection attempts to place an identical lock on the same database it will be denied.
<em>Returns:</em>:</p>
</p>
* 0: Failure: Another connection has already placed the same lock.</p>
<p>Locks can be removed by unlock() or unlockall() or will be automatically removed at the end of a transaction or when the connection is closed.
* "" Failure: The lock has already been placed.</p>
</p>
* 1: Success: A new lock has been placed.</p>
<p>If the same process attempts to place an identical lock more than once it may be denied (if not in a transaction) or succeed but be ignored (if in a transaction).
</p>
<p>Locks can be used to avoid processing a transaction simultaneously with another connection only to have one of them fail due to mutually updating the same records.
</p>
<p><em>Returns:</em>:
</p>
<p>* 0: Failure: Another connection has already placed the same lock.
</p>
<p>* "" Failure: The lock has already been placed.
</p>
<p>* 1: Success: A new lock has been placed.
</p>
* 2: Success: The lock has already been placed and the connection is in a transaction.
* 2: Success: The lock has already been placed and the connection is in a transaction.


Line 1,812: Line 2,174:


</td></tr>
</td></tr>
<tr><td>if</td><td>file.unlock(key)</td><td>Removes a db lock placed by the lock function.</p>
<tr><td>if</td><td>file.unlock(key)</td><td><p>Removes a db lock placed by the lock function.
Only locks placed on the specified connection can be removed.</p>
</p>
Locks cannot be removed while a connection is in a transaction.</p>
<p>Only locks placed on the specified connection can be removed.
</p>
<p>Locks cannot be removed while a connection is in a transaction.
</p>
<em>Returns:</em> False if the lock is not present in a connection.
<em>Returns:</em> False if the lock is not present in a connection.


Line 1,823: Line 2,188:


</td></tr>
</td></tr>
<tr><td>if</td><td>file.unlockall()</td><td>Removes all db locks placed by the lock function in the specified connection.</p>
<tr><td>if</td><td>file.unlockall()</td><td><p>Removes all db locks placed by the lock function in the specified connection.
</p>
Locks cannot be removed while in a transaction.
Locks cannot be removed while in a transaction.


Line 1,832: Line 2,198:


</td></tr>
</td></tr>
<tr><td></td><td>record.write(file, key)</td><td>Writes a record into a db file given a unique primary key.</p>
<tr><td></td><td>record.write(file, key)</td><td><p>Writes a record into a db file given a unique primary key.
Either inserts a new record or updates an existing record.</p>
</p>
<em>Returns:</em> Nothing since writes always succeed.</p>
<p>Either inserts a new record or updates an existing record.
<em>Throws:</em> VarDBException if the file does not exist. Like most db functions.</p>
</p>
<p><em>Returns:</em> Nothing since writes always succeed.
</p>
<p><em>Throws:</em> VarDBException if the file does not exist. Like most db functions.
</p>
Any memory cached record is deleted.
Any memory cached record is deleted.


Line 1,846: Line 2,216:


</td></tr>
</td></tr>
<tr><td>if</td><td>record.read(file, key)</td><td>Reads a record from a db file for a given key.</p>
<tr><td>if</td><td>record.read(file, key)</td><td><p>Reads a record from a db file for a given key.
<em>file:</em> A db filename or a var opened to a db file.</p>
</p>
<em>key:</em> The key of the record to be read.</p>
<p><em>file:</em> A db filename or a var opened to a db file.
<em>Returns:</em> False if the key doesnt exist</p>
</p>
<em>var:</em> Contains the record if it exists or is unassigned if not.</p>
<p><em>key:</em> The key of the record to be read.
</p>
<p><em>Returns:</em> False if the key doesnt exist
</p>
<p><em>var:</em> Contains the record if it exists or is unassigned if not.
</p>
A special case of the key being "%RECORDS%" results in a fictitious "record" being returned as an FM separated list of all the keys in the db file up to a maximum size of 4Mib, sorted in natural order.
A special case of the key being "%RECORDS%" results in a fictitious "record" being returned as an FM separated list of all the keys in the db file up to a maximum size of 4Mib, sorted in natural order.


Line 1,860: Line 2,235:


</td></tr>
</td></tr>
<tr><td>if</td><td>file.deleterecord(key)</td><td>Deletes a record from a db file given a key.</p>
<tr><td>if</td><td>file.deleterecord(key)</td><td><p>Deletes a record from a db file given a key.
<em>Returns:</em> False if the key doesnt exist</p>
</p>
Any memory cached record is deleted.</p>
<p><em>Returns:</em> False if the key doesnt exist
</p>
<p>Any memory cached record is deleted.
</p>
deleterecord(in file), a one argument free function, is available that deletes multiple records using the currently active select list.
deleterecord(in file), a one argument free function, is available that deletes multiple records using the currently active select list.


Line 1,871: Line 2,249:


</td></tr>
</td></tr>
<tr><td>if</td><td>record.insertrecord(file, key)</td><td>Inserts a new record in a db file.</p>
<tr><td>if</td><td>record.insertrecord(file, key)</td><td><p>Inserts a new record in a db file.
<em>Returns:</em> False if the key already exists</p>
</p>
<p><em>Returns:</em> False if the key already exists
</p>
Any memory cached record is deleted.
Any memory cached record is deleted.


Line 1,882: Line 2,262:


</td></tr>
</td></tr>
<tr><td>if</td><td>record.updaterecord(file, key)</td><td>Updates an existing record in a db file.</p>
<tr><td>if</td><td>record.updaterecord(file, key)</td><td><p>Updates an existing record in a db file.
<em>Returns:</em> False if no record with the given key exists.</p>
</p>
<p><em>Returns:</em> False if no record with the given key exists.
</p>
Any memory cached record is deleted.
Any memory cached record is deleted.


Line 1,893: Line 2,275:


</td></tr>
</td></tr>
<tr><td>if</td><td>record.updatekey(key, newkey)</td><td>Updates the key of an existing record in a db file.</p>
<tr><td>if</td><td>record.updatekey(key, newkey)</td><td><p>Updates the key of an existing record in a db file.
<em>Returns:</em> True if successful or false if no record with the given key exists, or a record with newkey already exists</p>
</p>
<p><em>Returns:</em> True if successful or false if no record with the given key exists, or a record with newkey already exists
</p>
Any memory cached records of either key are deleted.
Any memory cached records of either key are deleted.


Line 1,919: Line 2,303:


</td></tr>
</td></tr>
<tr><td></td><td>record.writec(file, key)</td><td>"Write cache" Writes a record and key into a memory cached "db file".</p>
<tr><td></td><td>record.writec(file, key)</td><td><p>"Write cache" Writes a record and key into a memory cached "db file".
The actual database file is NOT updated.</p>
</p>
writec() either updates an existing cache record if the key already exists or otherwise inserts a new record into the cache.</p>
<p>The actual database file is NOT updated.
It always succeeds so no result code is returned.</p>
</p>
<p>writec() either updates an existing cache record if the key already exists or otherwise inserts a new record into the cache.
</p>
<p>It always succeeds so no result code is returned.
</p>
Neither the db file nor the record key need to actually exist in the actual db.
Neither the db file nor the record key need to actually exist in the actual db.


Line 1,932: Line 2,320:


</td></tr>
</td></tr>
<tr><td>if</td><td>record.readc(file, key)</td><td>"Read cache" Same as "read() but first reads from a memory cache.</p>
<tr><td>if</td><td>record.readc(file, key)</td><td><p>"Read cache" Same as "read() but first reads from a memory cache.
1. Tries to read from a memory cache. Returns true if successful.</p>
</p>
2a. Tries to read from the actual db file and returns false if unsuccessful.</p>
<p>1. Tries to read from a memory cache. Returns true if successful.
2b. Writes the record and key to the memory cache and returns true.</p>
</p>
<p>2a. Tries to read from the actual db file and returns false if unsuccessful.
</p>
<p>2b. Writes the record and key to the memory cache and returns true.
</p>
Cached db file data lives in exodus process memory and is lost when the process terminates or clearcache() is called.
Cached db file data lives in exodus process memory and is lost when the process terminates or clearcache() is called.


Line 1,948: Line 2,340:


</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.deletec(key)</td><td>Deletes a record and key from a memory cached "file".</p>
<tr><td>if</td><td>dbfile.deletec(key)</td><td><p>Deletes a record and key from a memory cached "file".
The actual database file is NOT updated.</p>
</p>
<p>The actual database file is NOT updated.
</p>
<em>Returns:</em> False if the key doesnt exist
<em>Returns:</em> False if the key doesnt exist


Line 1,958: Line 2,352:


</td></tr>
</td></tr>
<tr><td></td><td>conn.clearcache()</td><td>Clears the memory cache of all records for the given connection</p>
<tr><td></td><td>conn.clearcache()</td><td><p>Clears the memory cache of all records for the given connection
</p>
All future cache readc() function calls will be forced to obtain records from the actual database and refresh the cache.
All future cache readc() function calls will be forced to obtain records from the actual database and refresh the cache.


Line 1,966: Line 2,361:


</td></tr>
</td></tr>
<tr><td>var=</td><td>strvar.xlate(filename, fieldno, mode)</td><td>The xlate ("translate") function is similar to readf() but, when called as an exodus program member function, it can be used efficiently with exodus file dictionaries using column names and functions and multivalued data.</p>
<tr><td>var=</td><td>strvar.xlate(filename, fieldno, mode)</td><td><p>The xlate ("translate") function is similar to readf() but, when called as an exodus program member function, it can be used efficiently with exodus file dictionaries using column names and functions and multivalued data.
<em>Arguments:</em></p>
</p>
<em>strvar:</em> Used as the primary key to lookup a field in a given file and field no or field name.</p>
<p><em>Arguments:</em>
<em>filename:</em> The db file in which to look up data.</p>
</p>
If var key is multivalued then a multivalued field is returned.</p>
<p>strvar: Used as the primary key to lookup a field in a given file and field no or field name.
<em>fieldno:</em> Determines which field of the record is returned.</p>
</p>
* Integer returns that field number</p>
<p><em>filename:</em> The db file in which to look up data.
* 0 means return the key unchanged.</p>
</p>
* "" means return the whole record.</p>
<p>If var key is multivalued then a multivalued field is returned.
<em>mode:</em> Determines what is returned if the record does not exist for the given key and file.</p>
</p>
* "X" returns ""</p>
<p><em>fieldno:</em> Determines which field of the record is returned.
</p>
<p>* Integer returns that field number
</p>
<p>* 0 means return the key unchanged.
</p>
<p>* "" means return the whole record.
</p>
<p><em>mode:</em> Determines what is returned if the record does not exist for the given key and file.
</p>
<p>* "X" returns ""
</p>
* "C" returns the key unconverted.
* "C" returns the key unconverted.


Line 1,990: Line 2,396:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>dbfile.select(sort_select_command = "")</td><td>Create an active select list of keys of a database file.</p>
<tr><td>if</td><td>dbfile.select(sort_select_command = "")</td><td><p>Create an active select list of keys of a database file.
The select(command) function searches and orders database records for subsequent processing given an English language-like command.</p>
</p>
The primary job of a database, beyond mere storage and retrieval of information, is to allow rapid searching and ordering of information on demand.</p>
<p>The select(command) function searches and orders database records for subsequent processing given an English language-like command.
In Exodus, searching and ordering of information is known as "sort/select" and is performed by the select() function.</p>
</p>
Executing the select() function creates an "active select list" which can then be consumed by the readnext() function.</p>
<p>The primary job of a database, beyond mere storage and retrieval of information, is to allow rapid searching and ordering of information on demand.
<em>dbfile:</em> A opened database file or file name, or an open connection or an empty var for default connections. Subsequent readnext calls must use the same.</p>
</p>
<em>sort_select_command:</em> A natural language command using dictionary field names. The command can be blank if a dbfile or filename is given in dbfile or just a file name and all keys will be selected in undefined order.</p>
<p>In Exodus, searching and ordering of information is known as "sort/select" and is performed by the select() function.
<em>Example:</em> "select xo_clients with type 'B' and with balance ge 100 by type by name"</p>
</p>
<em>Option:</em> "(R)" appended to the sort_select_command acquires the database records as well.</p>
<p>Executing the select() function creates an "active select list" which can then be consumed by the readnext() function.
<em>Returns:</em> True if any records are selected or false if none.</p>
</p>
<em>Throws:</em> VarDBException in case of any syntax error in the command.</p>
<p><em>dbfile:</em> A opened database file or file name, or an open connection or an empty var for default connections. Subsequent readnext calls must use the same.
</p>
<p><em>sort_select_command:</em> A natural language command using dictionary field names. The command can be blank if a dbfile or filename is given in dbfile or just a file name and all keys will be selected in undefined order.
</p>
<p><em>Example:</em> "select xo_clients with type 'B' and with balance ge 100 by type by name"
</p>
<p><em>Option:</em> "(R)" appended to the sort_select_command acquires the database records as well.
</p>
<p><em>Returns:</em> True if any records are selected or false if none.
</p>
<p><em>Throws:</em> VarDBException in case of any syntax error in the command.
</p>
Active select lists created using var.select()'s member function syntax cannot be consumed by the free function form of readnext() and vice versa.
Active select lists created using var.select()'s member function syntax cannot be consumed by the free function form of readnext() and vice versa.


Line 2,013: Line 2,430:


</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.selectkeys(keys)</td><td>Create an active select list from a string of keys.</p>
<tr><td>if</td><td>dbfile.selectkeys(keys)</td><td><p>Create an active select list from a string of keys.
Similar to select() but creates the list directly from a var.</p>
</p>
<em>keys:</em> An FM separated list of keys or key^VM^valueno pairs.</p>
<p>Similar to select() but creates the list directly from a var.
</p>
<p><em>keys:</em> An FM separated list of keys or key^VM^valueno pairs.
</p>
<em>Returns:</em> True if any keys are provided or false if not.
<em>Returns:</em> True if any keys are provided or false if not.


Line 2,027: Line 2,447:


</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.hasnext()</td><td>Checks if a select list is active.</p>
<tr><td>if</td><td>dbfile.hasnext()</td><td><p>Checks if a select list is active.
<em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.</p>
</p>
<em>Returns:</em> True if a select list is active and false if not.</p>
<p><em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.
</p>
<p><em>Returns:</em> True if a select list is active and false if not.
</p>
If it returns true then a call to readnext() will return a database record key, otherwise not.
If it returns true then a call to readnext() will return a database record key, otherwise not.


Line 2,042: Line 2,465:


</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.readnext(out key)</td><td>Acquires and consumes one key from an active select list of database record keys.</p>
<tr><td>if</td><td>dbfile.readnext(out key)</td><td><p>Acquires and consumes one key from an active select list of database record keys.
<em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.</p>
</p>
<em>key:</em> Returns the first (next) key present in an active select list or "" if no select list is active.</p>
<p><em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.
<em>Returns:</em> True if a list is active and a key is available, false if not.</p>
</p>
Each call to readnext consumes one key from the list.</p>
<p><em>key:</em> Returns the first (next) key present in an active select list or "" if no select list is active.
Once all the keys in an active select list have been consumed by calls to readnext, the list becomes inactive.</p>
</p>
See select() for example code.</p>
<p><em>Returns:</em> True if a list is active and a key is available, false if not.
</p>
<p>Each call to readnext consumes one key from the list.
</p>
<p>Once all the keys in an active select list have been consumed by calls to readnext, the list becomes inactive.
</p>
<p>See select() for example code.
</p>
</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.readnext(out key, out valueno)</td><td>Similar to readnext(key) but multivalued.</p>
<tr><td>if</td><td>dbfile.readnext(out key, out valueno)</td><td><p>Similar to readnext(key) but multivalued.
If the active list was ordered by multivalued database fields then pairs of key and multivalue number will be available to the readnext function.</p>
</p>
<p>If the active list was ordered by multivalued database fields then pairs of key and multivalue number will be available to the readnext function.
</p>
</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.readnext(out record, out key, out valueno)</td><td>Similar to readnext(key) but acquires the database record as well.</p>
<tr><td>if</td><td>dbfile.readnext(out record, out key, out valueno)</td><td><p>Similar to readnext(key) but acquires the database record as well.
<em>record:</em> Returns the next database record from the select list assuming that the select list was created with the (R) option otherwise "" if not.</p>
</p>
<em>key:</em> Returns the next database record key in the select list.</p>
<p><em>record:</em> Returns the next database record from the select list assuming that the select list was created with the (R) option otherwise "" if not.
</p>
<p><em>key:</em> Returns the next database record key in the select list.
</p>
<em>valueno:</em> The multivalue number if the select list was ordered on multivalued database record fields or 1 if not.
<em>valueno:</em> The multivalue number if the select list was ordered on multivalued database record fields or 1 if not.


Line 2,069: Line 2,504:


</td></tr>
</td></tr>
<tr><td></td><td>dbfile.clearselect()</td><td>Deactivates an active select list.</p>
<tr><td></td><td>dbfile.clearselect()</td><td><p>Deactivates an active select list.
<em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.</p>
</p>
<em>Returns:</em> Nothing</p>
<p><em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.
</p>
<p><em>Returns:</em> Nothing
</p>
Has no effect if no select list is active for dbfile.
Has no effect if no select list is active for dbfile.


Line 2,082: Line 2,520:


</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.savelist(listname)</td><td>Stores an active select list for later retrieval.</p>
<tr><td>if</td><td>dbfile.savelist(listname)</td><td><p>Stores an active select list for later retrieval.
<em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.</p>
</p>
<em>listname:</em> A suitable name that will be required for later retrieval.</p>
<p><em>dbfile:</em> A file or connection var used in a prior select, selectkeys or getlist function call.
<em>Returns:</em> True if saved successfully or false if there was no active list to be saved.</p>
</p>
Any existing list with the same name will be overwritten.</p>
<p><em>listname:</em> A suitable name that will be required for later retrieval.
Only the remaining unconsumed part of the active select list is saved.</p>
</p>
Saved lists are stand-alone and are not tied to specific database files although they usually hold keys related to specific files.</p>
<p><em>Returns:</em> True if saved successfully or false if there was no active list to be saved.
Saved lists can be created from one file and used to access another.</p>
</p>
savelist() merely writes an FM separated string of keys as a record in the "lists" database file using the list name as the key of the record.</p>
<p>Any existing list with the same name will be overwritten.
If a saved list is very long, additional blocks of keys for the same list may be stored with keys like listname*2, listname*3 etc.</p>
</p>
Select lists saved in the lists database file may be created, deleted and listed like database records in any other database file.
<p>Only the remaining unconsumed part of the active select list is saved.
 
</p>
<pre><code class='hljs-ncdecl language-javascript'>var clients = "xo_clients";
<p>Saved lists are stand-alone and are not tied to specific database files although they usually hold keys related to specific files.
</p>
<p>Saved lists can be created from one file and used to access another.
</p>
<p>savelist() merely writes an FM separated string of keys as a record in the "lists" database file using the list name as the key of the record.
</p>
<p>If a saved list is very long, additional blocks of keys for the same list may be stored with keys like listname*2, listname*3 etc.
</p>
Select lists saved in the lists database file may be created, deleted and listed like database records in any other database file.
 
<pre><code class='hljs-ncdecl language-javascript'>var clients = "xo_clients";
if (clients.select("with type 'B' by name")) {
if (clients.select("with type 'B' by name")) {
}
}
Line 2,103: Line 2,551:


</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.getlist(listname)</td><td>Retrieve and reactivate a saved select list.</p>
<tr><td>if</td><td>dbfile.getlist(listname)</td><td><p>Retrieve and reactivate a saved select list.
<em>dbfile:</em> A file or connection var to be used by subsequent readnext function calls.</p>
</p>
<em>listname:</em> The name of an existing list in the "lists" database file, either created by savelist or manually.</p>
<p><em>dbfile:</em> A file or connection var to be used by subsequent readnext function calls.
<em>Returns:</em> True if the list was successfully retrieved and activated, or false if the list name doesnt exist.</p>
</p>
Any currently active select list is replaced.</p>
<p><em>listname:</em> The name of an existing list in the "lists" database file, either created by savelist or manually.
</p>
<p><em>Returns:</em> True if the list was successfully retrieved and activated, or false if the list name doesnt exist.
</p>
<p>Any currently active select list is replaced.
</p>
Retrieving a list does not delete it and a list can be retrieved more than once until specifically deleted.
Retrieving a list does not delete it and a list can be retrieved more than once until specifically deleted.


Line 2,122: Line 2,575:


</td></tr>
</td></tr>
<tr><td>if</td><td>dbfile.deletelist(listname)</td><td>Delete a saved select list.</p>
<tr><td>if</td><td>dbfile.deletelist(listname)</td><td><p>Delete a saved select list.
<em>dbfile:</em> A file or connection to the desired database.</p>
</p>
<em>listname:</em> The name of an existing list in the "lists" database file.</p>
<p><em>dbfile:</em> A file or connection to the desired database.
</p>
<p><em>listname:</em> The name of an existing list in the "lists" database file.
</p>
<em>Returns:</em> True if successful or false if the list name doesnt exist.
<em>Returns:</em> True if successful or false if the list name doesnt exist.


Line 2,138: Line 2,594:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>var::date()</td><td>Number of whole days since pick epoch 1967-12-31 00:00:00 UTC. Negative for dates before.</p>
<tr><td>var=</td><td>var::date()</td><td><p>Number of whole days since pick epoch 1967-12-31 00:00:00 UTC. Negative for dates before.
</p>
e.g. was 20821 from 2025-01-01 00:00:00 UTC for 24 hours
e.g. was 20821 from 2025-01-01 00:00:00 UTC for 24 hours


Line 2,146: Line 2,603:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::time()</td><td>Number of whole seconds since last 00:00:00 (UTC).</p>
<tr><td>var=</td><td>var::time()</td><td><p>Number of whole seconds since last 00:00:00 (UTC).
e.g. 43200 if time is 12:00</p>
</p>
<p>e.g. 43200 if time is 12:00
</p>
Range 0 - 86399 since there are 24*60*60 (86400) seconds in a day.
Range 0 - 86399 since there are 24*60*60 (86400) seconds in a day.


Line 2,155: Line 2,614:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::ostime()</td><td>Number of fractional seconds since last 00:00:00 (UTC).</p>
<tr><td>var=</td><td>var::ostime()</td><td><p>Number of fractional seconds since last 00:00:00 (UTC).
A floating point with approx. nanosecond resolution depending on hardware.</p>
</p>
<p>A floating point with approx. nanosecond resolution depending on hardware.
</p>
e.g. 23343.704387955 approx. 06:29:03 UTC
e.g. 23343.704387955 approx. 06:29:03 UTC


Line 2,164: Line 2,625:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::ostimestamp()</td><td>Number of fractional days since pick epoch 1967-12-31 00:00:00 UTC. Negative for dates before.</p>
<tr><td>var=</td><td>var::ostimestamp()</td><td><p>Number of fractional days since pick epoch 1967-12-31 00:00:00 UTC. Negative for dates before.
A floating point with approx. nanosecond resolution depending on hardware.</p>
</p>
<p>A floating point with approx. nanosecond resolution depending on hardware.
</p>
e.g. Was 20821.99998842593 around 2025-01-01 23:59:59 UTC
e.g. Was 20821.99998842593 around 2025-01-01 23:59:59 UTC


Line 2,181: Line 2,644:


</td></tr>
</td></tr>
<tr><td></td><td>var::ossleep(milliseconds)</td><td>Sleep/pause/wait for a number of milliseconds</p>
<tr><td></td><td>var::ossleep(milliseconds)</td><td><p>Sleep/pause/wait for a number of milliseconds
</p>
Releases the processor if not needed for a period of time or a delay is required.
Releases the processor if not needed for a period of time or a delay is required.


Line 2,189: Line 2,653:


</td></tr>
</td></tr>
<tr><td>var=</td><td>file_dir_list.oswait(milliseconds)</td><td>Sleep/pause/wait up to a given number of milliseconds or until any changes occur in an FM delimited list of directories and/or files.</p>
<tr><td>var=</td><td>file_dir_list.oswait(milliseconds)</td><td><p>Sleep/pause/wait up to a given number of milliseconds or until any changes occur in an FM delimited list of directories and/or files.
Any terminal input (e.g. a key press) will also terminate the wait.</p>
</p>
An FM array of event information is returned. See below.</p>
<p>Any terminal input (e.g. a key press) will also terminate the wait.
Multiple events are returned in multivalues.
</p>
<p>An FM array of event information is returned. See below.
</p>
<p>Multiple events are returned in multivalues.


<pre><code class='hljs-ncdecl language-javascript'>let v1 = ".^/etc/hosts"_var.oswait(100); /// e.g. "IN_CLOSE_WRITE^/etc^hosts^f"_var
<pre><code class='hljs-ncdecl language-javascript'>let v1 = ".^/etc/hosts"_var.oswait(100); /// e.g. "IN_CLOSE_WRITE^/etc^hosts^f"_var
Line 2,198: Line 2,665:
let v2 = oswait(".^/etc/hosts"_var, 100);</code></pre>
let v2 = oswait(".^/etc/hosts"_var, 100);</code></pre>


Returned array fields</p>
Returned array fields
1. Event type codes</p>
</p>
2. dirpaths</p>
<p>1. Event type codes
3. filenames</p>
</p>
4. d=dir, f=file</p>
<p>2. dirpaths
<pre></p>
</p>
Possible event type codes are as follows:</p>
<p>3. filenames
* IN_CLOSE_WRITE - A file opened for writing was closed</p>
</p>
* IN_ACCESS      - Data was read from file</p>
<p>4. d=dir, f=file
* IN_MODIFY      - Data was written to file</p>
</p>
* IN_ATTRIB      - File attributes changed</p>
<p><pre>
* IN_CLOSE      - File was closed (read or write)</p>
</p>
* IN_MOVED_FROM  - File was moved away from watched directory</p>
<p>Possible event type codes are as follows:
* IN_MOVED_TO    - File was moved into watched directory</p>
</p>
* IN_MOVE        - File was moved (in or out of directory)</p>
<p>* IN_CLOSE_WRITE - A file opened for writing was closed
* IN_CREATE      - A file was created in the directory</p>
</p>
* IN_DELETE      - A file was deleted from the directory</p>
<p>* IN_ACCESS      - Data was read from file
* IN_DELETE_SELF - Directory or file under observation was deleted</p>
</p>
* IN_MOVE_SELF  - Directory or file under observation was moved</p>
<p>* IN_MODIFY      - Data was written to file
</pre></p>
</p>
</td></tr>
<p>* IN_ATTRIB      - File attributes changed
</table>
</p>
<h5 id=OS_File_I/O>OS File I/O</h5>
<p>* IN_CLOSE      - File was closed (read or write)
 
</p>
<table class=wikitable>
<p>* IN_MOVED_FROM  - File was moved away from watched directory
</p>
<p>* IN_MOVED_TO    - File was moved into watched directory
</p>
<p>* IN_MOVE        - File was moved (in or out of directory)
</p>
<p>* IN_CREATE      - A file was created in the directory
</p>
<p>* IN_DELETE      - A file was deleted from the directory
</p>
<p>* IN_DELETE_SELF - Directory or file under observation was deleted
</p>
<p>* IN_MOVE_SELF  - Directory or file under observation was moved
</p>
<p></pre>
</p>
</td></tr>
</table>
<h5 id=OS_File_I/O>OS File I/O</h5>
 
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>osfilevar.osopen(osfilename, utf8 = true)</td><td>Initialises an os file handle var that can be used for random read and write</p>
<tr><td>if</td><td>osfilevar.osopen(osfilename, utf8 = true)</td><td><p>Initialises an os file handle var that can be used for random read and write
<em>osfilename:</em> The name of an existing os file name including path.</p>
</p>
<em>utf8:</em> Defaults to true which causes trimming of partial UTF-8 Unicode byte sequences from the end of osbreads. For raw untrimmed osbreads pass tf8 = false;</p>
<p><em>osfilename:</em> The name of an existing os file name including path.
<em>osfilevar:</em> [out] To be used in subsequent calls to osbread() and osbwrite()</p>
</p>
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Target doesnt exist, permissions etc.</p>
<p><em>utf8:</em> Defaults to true which causes trimming of partial UTF-8 Unicode byte sequences from the end of osbreads. For raw untrimmed osbreads pass tf8 = false;
</p>
<p><em>osfilevar:</em> [out] To be used in subsequent calls to osbread() and osbwrite()
</p>
<p><em>Returns:</em> True if successful or false if not possible for any reason. e.g. Target doesnt exist, permissions etc.
</p>
The file will be opened for writing if possible otherwise for reading.
The file will be opened for writing if possible otherwise for reading.


Line 2,239: Line 2,731:


</td></tr>
</td></tr>
<tr><td>if</td><td>osfilevar.osbwrite(osfilevar, io offset)</td><td>Writes data to an existing os file starting at a given byte offset (0 based).</p>
<tr><td>if</td><td>osfilevar.osbwrite(osfilevar, io offset)</td><td><p>Writes data to an existing os file starting at a given byte offset (0 based).
</p>
See osbread for more info.
See osbread for more info.


Line 2,250: Line 2,743:


</td></tr>
</td></tr>
<tr><td>if</td><td>osfilevar.osbread(osfilevar, io offset, length)</td><td>Reads length bytes from an existing os file starting at a given byte offset (0 based).</p>
<tr><td>if</td><td>osfilevar.osbread(osfilevar, io offset, length)</td><td><p>Reads length bytes from an existing os file starting at a given byte offset (0 based).
The osfilevar file handle may either be initialised by osopen or be just be a normal string variable holding the path and name of the os file.</p>
</p>
After reading, the offset is updated to point to the correct offset for a subsequent sequential read.</p>
<p>The osfilevar file handle may either be initialised by osopen or be just be a normal string variable holding the path and name of the os file.
</p>
<p>After reading, the offset is updated to point to the correct offset for a subsequent sequential read.
</p>
If reading UTF8 data (the default) then the length of data actually returned may be a few bytes shorter than requested in order to be a complete number of UTF-8 code points.
If reading UTF8 data (the default) then the length of data actually returned may be a few bytes shorter than requested in order to be a complete number of UTF-8 code points.


Line 2,262: Line 2,758:


</td></tr>
</td></tr>
<tr><td></td><td>osfilevar.osclose()</td><td>Removes an osfilevar handle from the internal memory cache of os file handles. This frees up both exodus process memory and operating system resources.</p>
<tr><td></td><td>osfilevar.osclose()</td><td><p>Removes an osfilevar handle from the internal memory cache of os file handles. This frees up both exodus process memory and operating system resources.
</p>
It is advisable to osclose any file handles after use, regardless of whether they were specifically opened using osopen or not, especially in long running programs. Exodus performs caching of internal os file handles per thread and os file. If not closed, then the operating system will probably not flush deleted files from storage until the process is terminated. This can potentially create an memory issue or file system resource issue especially if osopening/osreading/oswriting many perhaps temporary files in a long running process.
It is advisable to osclose any file handles after use, regardless of whether they were specifically opened using osopen or not, especially in long running programs. Exodus performs caching of internal os file handles per thread and os file. If not closed, then the operating system will probably not flush deleted files from storage until the process is terminated. This can potentially create an memory issue or file system resource issue especially if osopening/osreading/oswriting many perhaps temporary files in a long running process.


Line 2,270: Line 2,767:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.oswrite(osfilename, codepage = "")</td><td>Create a complete os file from a var.</p>
<tr><td>if</td><td>strvar.oswrite(osfilename, codepage = "")</td><td><p>Create a complete os file from a var.
<em>strvar:</em> The text or data to be used to create the file.</p>
</p>
<em>osfilename:</em> Absolute or relative path and filename to be written. Any existing os file is removed first.</p>
<p><em>strvar:</em> The text or data to be used to create the file.
<em>codepage:</em> If specified then output is converted from UTF-8 to that codepage before being written. Otherwise no conversion is done.</p>
</p>
<p><em>osfilename:</em> Absolute or relative path and filename to be written. Any existing os file is removed first.
</p>
<p><em>codepage:</em> If specified then output is converted from UTF-8 to that codepage before being written. Otherwise no conversion is done.
</p>
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Path is not writeable, permissions etc.
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Path is not writeable, permissions etc.


Line 2,283: Line 2,784:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.osread(osfilename, codepage = "")</td><td>Read a complete os file into a var.</p>
<tr><td>if</td><td>strvar.osread(osfilename, codepage = "")</td><td><p>Read a complete os file into a var.
<em>osfilename:</em> Absolute or relative path and filename to be read.</p>
</p>
<em>codepage:</em> If specified then input is converted from that codepage to UTF-8 after being read. Otherwise no conversion is done.</p>
<p><em>osfilename:</em> Absolute or relative path and filename to be read.
<em>strvar:</em> [out] is currently set to "" in case of any failure but this is may be changed in a future release to either force var to be unassigned or to leave it untouched. To guarantee future behaviour either add a line 'xxxx.defaulter("")' or set var manually in case osread() returns false. Or use the one argument free function version of osread() which always returns "" in case of failure to read.</p>
</p>
<p><em>codepage:</em> If specified then input is converted from that codepage to UTF-8 after being read. Otherwise no conversion is done.
</p>
<p><em>strvar:</em> [out] is currently set to "" in case of any failure but this is may be changed in a future release to either force var to be unassigned or to leave it untouched. To guarantee future behaviour either add a line 'xxxx.defaulter("")' or set var manually in case osread() returns false. Or use the one argument free function version of osread() which always returns "" in case of failure to read.
</p>
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. File doesnt exist, insufficient permissions etc.
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. File doesnt exist, insufficient permissions etc.


Line 2,297: Line 2,802:


</td></tr>
</td></tr>
<tr><td>if</td><td>osfile_or_dirname.osrename(new_dirpath_or_filepath)</td><td>Renames an os file or dir in the OS file system.</p>
<tr><td>if</td><td>osfile_or_dirname.osrename(new_dirpath_or_filepath)</td><td><p>Renames an os file or dir in the OS file system.
The source and target must exist in the same storage device.</p>
</p>
<em>osfile_or_dirname:</em> Absolute or relative path and file or dir name to be renamed.</p>
<p>The source and target must exist in the same storage device.
<em>new_dirpath_or_filepath:</em> Will not overwrite an existing os file or dir.</p>
</p>
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Target already exists, path is not writeable, permissions etc.</p>
<p><em>osfile_or_dirname:</em> Absolute or relative path and file or dir name to be renamed.
Uses std::filesystem::rename internally.
</p>
<p><em>new_dirpath_or_filepath:</em> Will not overwrite an existing os file or dir.
</p>
<p><em>Returns:</em> True if successful or false if not possible for any reason. e.g. Target already exists, path is not writeable, permissions etc.
</p>
Uses std::filesystem::rename internally.


<pre><code class='hljs-ncdecl language-javascript'>let from_osfilename = ostempdir() ^ "xo_gendoc_test.conf";
<pre><code class='hljs-ncdecl language-javascript'>let from_osfilename = ostempdir() ^ "xo_gendoc_test.conf";
Line 2,313: Line 2,823:


</td></tr>
</td></tr>
<tr><td>if</td><td>osfile_or_dirname.osmove(to_osfilename)</td><td>"Moves" an os file or dir within the os file system.</p>
<tr><td>if</td><td>osfile_or_dirname.osmove(to_osfilename)</td><td><p>"Moves" an os file or dir within the os file system.
Attempts osrename first, then oscopy followed by osremove original.</p>
</p>
<em>osfile_or_dirname:</em> Absolute or relative path and file or dir name to be moved.</p>
<p>Attempts osrename first, then oscopy followed by osremove original.
<em>to_osfilename:</em> Will not overwrite an existing os file or dir.</p>
</p>
<p><em>osfile_or_dirname:</em> Absolute or relative path and file or dir name to be moved.
</p>
<p><em>to_osfilename:</em> Will not overwrite an existing os file or dir.
</p>
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Source doesnt exist or cannot be accessed, target already exists, source or target is not writeable, permissions, storage space etc.
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Source doesnt exist or cannot be accessed, target already exists, source or target is not writeable, permissions, storage space etc.


Line 2,328: Line 2,842:


</td></tr>
</td></tr>
<tr><td>if</td><td>osfile_or_dirname.oscopy(to_osfilename)</td><td>Copies an os file or directory recursively within the os file system.</p>
<tr><td>if</td><td>osfile_or_dirname.oscopy(to_osfilename)</td><td><p>Copies an os file or directory recursively within the os file system.
<em>osfile_or_dirname:</em> Absolute or relative path and file or dir name to be copied.</p>
</p>
<em>to_osfilename:</em> Will overwrite an existing os file or merge into an existing dir.</p>
<p><em>osfile_or_dirname:</em> Absolute or relative path and file or dir name to be copied.
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Source doesnt exist or cannot be accessed, target is not writeable, permissions, storage space, etc.</p>
</p>
<p><em>to_osfilename:</em> Will overwrite an existing os file or merge into an existing dir.
</p>
<p><em>Returns:</em> True if successful or false if not possible for any reason. e.g. Source doesnt exist or cannot be accessed, target is not writeable, permissions, storage space, etc.
</p>
Uses std::filesystem::copy internally with recursive and overwrite options
Uses std::filesystem::copy internally with recursive and overwrite options


Line 2,342: Line 2,860:


</td></tr>
</td></tr>
<tr><td>if</td><td>osfilename.osremove()</td><td>Removes/deletes an os file from the OS file system.</p>
<tr><td>if</td><td>osfilename.osremove()</td><td><p>Removes/deletes an os file from the OS file system.
Will not remove directories. Use osrmdir() to remove directories</p>
</p>
<em>osfilename:</em> Absolute or relative path and file name to be removed.</p>
<p>Will not remove directories. Use osrmdir() to remove directories
</p>
<p><em>osfilename:</em> Absolute or relative path and file name to be removed.
</p>
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Target doesnt exist, path is not writeable, permissions etc.
<em>Returns:</em> True if successful or false if not possible for any reason. e.g. Target doesnt exist, path is not writeable, permissions etc.


Line 2,358: Line 2,879:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>dirpath.oslist(globpattern = "", mode = 0)</td><td>Get a list of os files and/or dirs.</p>
<tr><td>var=</td><td>dirpath.oslist(globpattern = "", mode = 0)</td><td><p>Get a list of os files and/or dirs.
<em>dirpath:</em> Absolute or relative dir path.</p>
</p>
<em>globpattern:</em> e.g. *.conf to be appended to the dirpath or a complete path plus glob pattern e.g. /etc/ *.conf.</p>
<p><em>dirpath:</em> Absolute or relative dir path.
<em>mode:</em> 0: default - Any regular files or dirs. 1 - Only regular os files. 2 - Only dirs.</p>
</p>
<p><em>globpattern:</em> e.g. *.conf to be appended to the dirpath or a complete path plus glob pattern e.g. /etc/ *.conf.
</p>
<p><em>mode:</em> 0: default - Any regular files or dirs. 1 - Only regular os files. 2 - Only dirs.
</p>
<em>Returns:</em> An FM delimited string containing all matching dir entries given a dir path
<em>Returns:</em> An FM delimited string containing all matching dir entries given a dir path


Line 2,370: Line 2,895:
<tr><td>var=</td><td>dirpath.oslistf(globpattern = "")</td><td>Same as oslist for files only</td></tr>
<tr><td>var=</td><td>dirpath.oslistf(globpattern = "")</td><td>Same as oslist for files only</td></tr>
<tr><td>var=</td><td>dirpath.oslistd(globpattern = "")</td><td>Same as oslist for files only</td></tr>
<tr><td>var=</td><td>dirpath.oslistd(globpattern = "")</td><td>Same as oslist for files only</td></tr>
<tr><td>var=</td><td>osfile_or_dirpath.osinfo(mode = 0)</td><td>Get dir info about an os file or dir.</p>
<tr><td>var=</td><td>osfile_or_dirpath.osinfo(mode = 0)</td><td><p>Get dir info about an os file or dir.
<em>Returns:</em> A short string containing size ^ FM ^ modified_time ^ FM ^ modified_time or "" if not a regular file or dir.</p>
</p>
<em>mode:</em> 0: default. 1: Must be a regular os file. 2: Must be an os dir.</p>
<p><em>Returns:</em> A short string containing size ^ FM ^ modified_time ^ FM ^ modified_time or "" if not a regular file or dir.
</p>
<p><em>mode:</em> 0: default. 1: Must be a regular os file. 2: Must be an os dir.
</p>
See also osfile() and osdir()
See also osfile() and osdir()


Line 2,380: Line 2,908:


</td></tr>
</td></tr>
<tr><td>var=</td><td>osfilename.osfile()</td><td>Get dir info of an os file.</p>
<tr><td>var=</td><td>osfilename.osfile()</td><td><p>Get dir info of an os file.
<em>osfilename:</em> Absolute or relative path and file name.</p>
</p>
<em>Returns:</em> A short string containing size ^ FM ^ modified_time ^ FM ^ modified_time or "" if not a regular file.</p>
<p><em>osfilename:</em> Absolute or relative path and file name.
</p>
<p><em>Returns:</em> A short string containing size ^ FM ^ modified_time ^ FM ^ modified_time or "" if not a regular file.
</p>
Alias for osinfo(1)
Alias for osinfo(1)


Line 2,390: Line 2,921:


</td></tr>
</td></tr>
<tr><td>var=</td><td>dirpath.osdir()</td><td>Get dir info of an os dir.</p>
<tr><td>var=</td><td>dirpath.osdir()</td><td><p>Get dir info of an os dir.
<em>dirpath:</em> Absolute or relative path and dir name.</p>
</p>
<em>Returns:</em> A short string containing FM ^ modified_time ^ FM ^ modified_time or "" if not a dir.</p>
<p><em>dirpath:</em> Absolute or relative path and dir name.
</p>
<p><em>Returns:</em> A short string containing FM ^ modified_time ^ FM ^ modified_time or "" if not a dir.
</p>
Alias for osinfo(2)
Alias for osinfo(2)


Line 2,400: Line 2,934:


</td></tr>
</td></tr>
<tr><td>if</td><td>dirpath.osmkdir()</td><td>Create a new os file system directory.</p>
<tr><td>if</td><td>dirpath.osmkdir()</td><td><p>Create a new os file system directory.
Parent dirs wil be created if necessary.</p>
</p>
<em>dirpath:</em> Absolute or relative path and dir name.</p>
<p>Parent dirs wil be created if necessary.
</p>
<p><em>dirpath:</em> Absolute or relative path and dir name.
</p>
<em>Returns:</em> True if successful.
<em>Returns:</em> True if successful.


Line 2,412: Line 2,949:


</td></tr>
</td></tr>
<tr><td>if</td><td>var::oscwd(newpath)</td><td>Changes the current working dir.</p>
<tr><td>if</td><td>var::oscwd(newpath)</td><td><p>Changes the current working dir.
<em>newpath:</em> An absolute or relative dir path and name.</p>
</p>
<p><em>newpath:</em> An absolute or relative dir path and name.
</p>
<em>Returns:</em> True if successful or false if not. e.g. Invalid dirpath, insufficient permission etc.
<em>Returns:</em> True if successful or false if not. e.g. Invalid dirpath, insufficient permission etc.


Line 2,423: Line 2,962:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::oscwd()</td><td>Gets the current dir path and name.</p>
<tr><td>var=</td><td>var::oscwd()</td><td><p>Gets the current dir path and name.
<em>Returns:</em> The current working dir path and name.</p>
</p>
<p><em>Returns:</em> The current working dir path and name.
</p>
e.g. "/root/exodus/cli/src/xo_test/aaa"
e.g. "/root/exodus/cli/src/xo_test/aaa"


Line 2,432: Line 2,973:


</td></tr>
</td></tr>
<tr><td>if</td><td>dirpath.osrmdir(evenifnotempty = false)</td><td>Removes (deletes) an os dir,</p>
<tr><td>if</td><td>dirpath.osrmdir(evenifnotempty = false)</td><td><p>Removes (deletes) an os dir,
<em>eventifnotempty:</em> If true any subdirs will also be removed/deleted recursively, otherwise the function will fail and return false.</p>
</p>
<p><em>eventifnotempty:</em> If true any subdirs will also be removed/deleted recursively, otherwise the function will fail and return false.
</p>
<em>Returns:</em> Returns true if successful or false if not. e.g dir doesnt exist, insufficient permission, not empty etc.
<em>Returns:</em> Returns true if successful or false if not. e.g dir doesnt exist, insufficient permission, not empty etc.


Line 2,447: Line 2,990:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>command.osshell()</td><td>Execute a shell command.</p>
<tr><td>if</td><td>command.osshell()</td><td><p>Execute a shell command.
<em>command:</em> An executable command to be interpreted by the default os shell.</p>
</p>
<em>Returns:</em> True if the process terminates with error status 0 and false otherwise.</p>
<p><em>command:</em> An executable command to be interpreted by the default os shell.
</p>
<p><em>Returns:</em> True if the process terminates with error status 0 and false otherwise.
</p>
Append "&>/dev/null" to the command to suppress terminal output.
Append "&>/dev/null" to the command to suppress terminal output.


Line 2,458: Line 3,004:


</td></tr>
</td></tr>
<tr><td>if</td><td>instr.osshellread(oscmd)</td><td>Same as osshell but captures and returns stdout</p>
<tr><td>if</td><td>instr.osshellread(oscmd)</td><td><p>Same as osshell but captures and returns stdout
<em>Returns:</em> The stout of the shell command.</p>
</p>
<p><em>Returns:</em> The stout of the shell command.
</p>
Append "2>&1" to the command to capture stderr/stdlog output as well.
Append "2>&1" to the command to capture stderr/stdlog output as well.


Line 2,470: Line 3,018:


</td></tr>
</td></tr>
<tr><td>if</td><td>outstr.osshellwrite(oscmd)</td><td>Same as osshell but provides stdin to the process</p>
<tr><td>if</td><td>outstr.osshellwrite(oscmd)</td><td><p>Same as osshell but provides stdin to the process
<em>Returns:</em> True if the process terminates with error status 0 and false otherwise.</p>
</p>
<p><em>Returns:</em> True if the process terminates with error status 0 and false otherwise.
</p>
Append "&> somefile" to the command to suppress and/or capture output.
Append "&> somefile" to the command to suppress and/or capture output.


Line 2,480: Line 3,030:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::ostempdir()</td><td>Get the tmp dir path and name.</p>
<tr><td>var=</td><td>var::ostempdir()</td><td><p>Get the tmp dir path and name.
</p>
<em>Returns:</em> A string e.g. "/tmp/"
<em>Returns:</em> A string e.g. "/tmp/"


Line 2,488: Line 3,039:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::ostempfile()</td><td>Create a temporary file</p>
<tr><td>var=</td><td>var::ostempfile()</td><td><p>Create a temporary file
</p>
<em>Returns:</em> The name of new temporary file e.g. "/tmp/~exoEcLj3C"
<em>Returns:</em> The name of new temporary file e.g. "/tmp/~exoEcLj3C"


Line 2,496: Line 3,048:


</td></tr>
</td></tr>
<tr><td></td><td>envvalue.ossetenv(envcode)</td><td>Set the value of an environment variable</p>
<tr><td></td><td>envvalue.ossetenv(envcode)</td><td><p>Set the value of an environment variable
<em>envcode:</em> The code of the env variable to set.</p>
</p>
<p><em>envcode:</em> The code of the env variable to set.
</p>
<em>envvalue:</em> The new value to set the env code to.
<em>envvalue:</em> The new value to set the env code to.


Line 2,506: Line 3,060:


</td></tr>
</td></tr>
<tr><td>if</td><td>envvalue.osgetenv(envcode)</td><td>Get the value of an environment variable.</p>
<tr><td>if</td><td>envvalue.osgetenv(envcode)</td><td><p>Get the value of an environment variable.
<em>envcode:</em> The code of the env variable to get or "" for all.</p>
</p>
<em>envvalue:</em> [out] Set to the value of the env variable if set otherwise "". If envcode is "" then envvalue is set to a dynamic array of all environment variables LIKE CODE1=VALUE1^CODE2=VALUE2...</p>
<p><em>envcode:</em> The code of the env variable to get or "" for all.
<em>Returns:</em> True if the envcode is set or false if not.</p>
</p>
osgetenv and ossetenv work with a per thread copy of the os process environment. This avoids multithreading issues but does not change the process environment. Child processes created by var::osshell() will not inherit any env variables set using ossetenv() so the oscommand will need to be prefixed to achieve the desired result.</p>
<p><em>envvalue:</em> [out] Set to the value of the env variable if set otherwise "". If envcode is "" then envvalue is set to a dynamic array of all environment variables LIKE CODE1=VALUE1^CODE2=VALUE2...
</p>
<p><em>Returns:</em> True if the envcode is set or false if not.
</p>
<p>osgetenv and ossetenv work with a per thread copy of the os process environment. This avoids multithreading issues but does not change the process environment. Child processes created by var::osshell() will not inherit any env variables set using ossetenv() so the oscommand will need to be prefixed to achieve the desired result.
</p>
For the actual system environment, see "man environ". extern char **environ; // environ is a pointer to an array of pointers to char* env pairs like xxx=yyy and the last pointer in the array is nullptr.
For the actual system environment, see "man environ". extern char **environ; // environ is a pointer to an array of pointers to char* env pairs like xxx=yyy and the last pointer in the array is nullptr.


Line 2,519: Line 3,078:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::ospid()</td><td>Get the current os process id</p>
<tr><td>var=</td><td>var::ospid()</td><td><p>Get the current os process id
</p>
<em>Returns:</em> A number e.g. 663237.
<em>Returns:</em> A number e.g. 663237.


Line 2,527: Line 3,087:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::ostid()</td><td>Get the current os thread process id</p>
<tr><td>var=</td><td>var::ostid()</td><td><p>Get the current os thread process id
</p>
<em>Returns:</em> A number e.g. 663237.
<em>Returns:</em> A number e.g. 663237.


Line 2,535: Line 3,096:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var::version()</td><td>Get the exodus library version info.</p>
<tr><td>var=</td><td>var::version()</td><td><p>Get the exodus library version info.
</p>
<em>Returns:</em> The git commit details as at the time the library was built.
<em>Returns:</em> The git commit details as at the time the library was built.


Line 2,549: Line 3,111:


</td></tr>
</td></tr>
<tr><td>if</td><td>strvar.setxlocale(newlocalecode)</td><td>Sets the current thread's default locale.</p>
<tr><td>if</td><td>strvar.setxlocale(newlocalecode)</td><td><p>Sets the current thread's default locale.
<em>strvar:</em> The new locale codepage code.</p>
</p>
<p><em>strvar:</em> The new locale codepage code.
</p>
True if successful
True if successful


Line 2,558: Line 3,122:


</td></tr>
</td></tr>
<tr><td>var=</td><td>var.getxlocale()</td><td>Gets the current thread's default locale.</p>
<tr><td>var=</td><td>var.getxlocale()</td><td><p>Gets the current thread's default locale.
</p>
<em>Returns:</em> A locale codepage code string.
<em>Returns:</em> A locale codepage code string.


Line 2,571: Line 3,136:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>expr</td><td>varstr.outputl(prefix = "")</td><td>Output to stdout with optional prefix.</p>
<tr><td>expr</td><td>varstr.outputl(prefix = "")</td><td><p>Output to stdout with optional prefix.
Appends an NL char.</p>
</p>
Is FLUSHED, not buffered.</p>
<p>Appends an NL char.
</p>
<p>Is FLUSHED, not buffered.
</p>
The raw string bytes are output. No character or byte conversion is performed.
The raw string bytes are output. No character or byte conversion is performed.


Line 2,583: Line 3,151:
<tr><td>expr</td><td>varstr.output(prefix = "")</td><td> Same as outputl() but doesnt append an NL char and is BUFFERED, not flushed.</td></tr>
<tr><td>expr</td><td>varstr.output(prefix = "")</td><td> Same as outputl() but doesnt append an NL char and is BUFFERED, not flushed.</td></tr>
<tr><td>expr</td><td>varstr.outputt(prefix = "")</td><td> Same as outputl() but appends a tab char instead of an NL char and is BUFFERED, not flushed.</td></tr>
<tr><td>expr</td><td>varstr.outputt(prefix = "")</td><td> Same as outputl() but appends a tab char instead of an NL char and is BUFFERED, not flushed.</td></tr>
<tr><td>expr</td><td>varstr.logputl(prefix = "")</td><td>Output to stdlog with optional prefix.</p>
<tr><td>expr</td><td>varstr.logputl(prefix = "")</td><td><p>Output to stdlog with optional prefix.
Appends an NL char.</p>
</p>
Is BUFFERED not flushed.</p>
<p>Appends an NL char.
</p>
<p>Is BUFFERED not flushed.
</p>
Any of the six types of field mark chars present are converted to their visible versions,
Any of the six types of field mark chars present are converted to their visible versions,


Line 2,594: Line 3,165:
</td></tr>
</td></tr>
<tr><td>expr</td><td>varstr.logput(prefix = "")</td><td> Same as logputl() but doesnt append an NL char.</td></tr>
<tr><td>expr</td><td>varstr.logput(prefix = "")</td><td> Same as logputl() but doesnt append an NL char.</td></tr>
<tr><td>expr</td><td>varstr.errputl(prefix = "")</td><td>Output to stderr with optional prefix.</p>
<tr><td>expr</td><td>varstr.errputl(prefix = "")</td><td><p>Output to stderr with optional prefix.
Appends an NL char.</p>
</p>
Is FLUSHED not buffered.</p>
<p>Appends an NL char.
</p>
<p>Is FLUSHED not buffered.
</p>
Any of the six types of field mark chars present are converted to their visible versions,
Any of the six types of field mark chars present are converted to their visible versions,


Line 2,605: Line 3,179:
</td></tr>
</td></tr>
<tr><td>expr</td><td>varstr.errput(prefix = "")</td><td> Same as errputl() but doesnt append an NL char and is BUFFERED not flushed.</td></tr>
<tr><td>expr</td><td>varstr.errput(prefix = "")</td><td> Same as errputl() but doesnt append an NL char and is BUFFERED not flushed.</td></tr>
<tr><td>expr</td><td>varstr.put(std::ostream& ostream1)</td><td>Output to a given stream.</p>
<tr><td>expr</td><td>varstr.put(std::ostream& ostream1)</td><td><p>Output to a given stream.
Is BUFFERED not flushed.</p>
</p>
The raw string bytes are output. No character or byte conversion is performed.</p>
<p>Is BUFFERED not flushed.
</p>
<p>The raw string bytes are output. No character or byte conversion is performed.
</p>
</td></tr>
</td></tr>
<tr><td></td><td>var().osflush()</td><td>Flush any and all buffered output to stdout and stdlog.
<tr><td></td><td>var().osflush()</td><td>Flush any and all buffered output to stdout and stdlog.
Line 2,621: Line 3,198:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>var.input(prompt = "")</td><td>Returns one line of input from stdin.</p>
<tr><td>if</td><td>var.input(prompt = "")</td><td><p>Returns one line of input from stdin.
<em>Returns:</em> True if successful or false if EOF or user pressed Esc or Ctrl+X in a terminal.</p>
</p>
<em>var:</em> [in] The default value for terminal input and editing. Ignored if not a terminal.</p>
<p><em>Returns:</em> True if successful or false if EOF or user pressed Esc or Ctrl+X in a terminal.
<em>var:</em> [out] Raw bytes up to but excluding the first new line char. In case of EOF or user pressed Esc or Ctrl+X in a terminal it will be changed to "".</p>
</p>
<em>Prompt:</em> If provided, it will be displayed on the terminal.</p>
<p><em>var:</em> [in] The default value for terminal input and editing. Ignored if not a terminal.
</p>
<p><em>var:</em> [out] Raw bytes up to but excluding the first new line char. In case of EOF or user pressed Esc or Ctrl+X in a terminal it will be changed to "".
</p>
<p><em>Prompt:</em> If provided, it will be displayed on the terminal.
</p>
Multibyte/UTF8 friendly.
Multibyte/UTF8 friendly.


Line 2,634: Line 3,216:


</td></tr>
</td></tr>
<tr><td>expr</td><td>var.inputn(nchars)</td><td>Get raw bytes from standard input.</p>
<tr><td>expr</td><td>var.inputn(nchars)</td><td><p>Get raw bytes from standard input.
Any new line chars are treated like any other bytes.</p>
</p>
Care must be taken to handle incomplete UTF8 byte sequences at the end of one block and the beginning of the next block.</p>
<p>Any new line chars are treated like any other bytes.
<em>Returns:</em> The requested number of bytes or fewer if not available.</p>
</p>
<em>nchars:</em></p>
<p>Care must be taken to handle incomplete UTF8 byte sequences at the end of one block and the beginning of the next block.
99 : Get up to 99 bytes or fewer if not available. Caution required with UTF8.</p>
</p>
⋅0 : Get all bytes presently available.</p>
<p><em>Returns:</em> The requested number of bytes or fewer if not available.
⋅1 : Same as keypressed(true). Deprecated.</p>
</p>
-1 : Same as keypressed(). Deprecated.</p>
<p><em>nchars:</em>
</p>
<p>99 : Get up to 99 bytes or fewer if not available. Caution required with UTF8.
</p>
<p>⋅0 : Get all bytes presently available.
</p>
<p>⋅1 : Same as keypressed(true). Deprecated.
</p>
<p>-1 : Same as keypressed(). Deprecated.
</p>
</td></tr>
</td></tr>
<tr><td>expr</td><td>var.keypressed(wait = false)</td><td>Return the code of the current terminal key pressed.</p>
<tr><td>expr</td><td>var.keypressed(wait = false)</td><td><p>Return the code of the current terminal key pressed.
<em>wait:</em> Defaults to false. True means wait for a key to be pressed if not already pressed.</p>
</p>
<em>Returns:</em> ASCII or key code defined according to terminal protocol.</p>
<p><em>wait:</em> Defaults to false. True means wait for a key to be pressed if not already pressed.
<em>Returns:</em> "" if stdin is not a terminal.</p>
</p>
e.g. The PgDn key if pressed might return an escape sequence like "\x1b[6~"</p>
<p><em>Returns:</em> ASCII or key code defined according to terminal protocol.
</p>
<p><em>Returns:</em> "" if stdin is not a terminal.
</p>
<p>e.g. The PgDn key if pressed might return an escape sequence like "\x1b[6~"
</p>
It only takes a few µsecs to return false if no key is pressed.
It only takes a few µsecs to return false if no key is pressed.


Line 2,656: Line 3,252:


</td></tr>
</td></tr>
<tr><td>if</td><td>var().isterminal(arg = 1)</td><td>Checks if one of stdin, stdout, stderr is a terminal or a file/pipe.</p>
<tr><td>if</td><td>var().isterminal(arg = 1)</td><td><p>Checks if one of stdin, stdout, stderr is a terminal or a file/pipe.
<em>arg:</em> 0 - stdin, 1 - stdout (Default), 2 - stderr.</p>
</p>
<em>Returns:</em> True if it is a terminal or false if it is a file or pipe.</p>
<p><em>arg:</em> 0 - stdin, 1 - stdout (Default), 2 - stderr.
Note that if the process is at the start or end of a pipeline, then only stdin or stdout will be a terminal.</p>
</p>
<p><em>Returns:</em> True if it is a terminal or false if it is a file or pipe.
</p>
<p>Note that if the process is at the start or end of a pipeline, then only stdin or stdout will be a terminal.
</p>
The type of stdout terminal can be obtained from the TERM environment variable.
The type of stdout terminal can be obtained from the TERM environment variable.


Line 2,667: Line 3,267:


</td></tr>
</td></tr>
<tr><td>if</td><td>var().hasinput(milliseconds = 0)</td><td>Checks if stdin has any bytes available for input.</p>
<tr><td>if</td><td>var().hasinput(milliseconds = 0)</td><td><p>Checks if stdin has any bytes available for input.
If no bytes are immediately available, the process sleeps for up to the given number of milliseconds, returning true immediately any bytes become available or false if the period expires without any bytes becoming available.</p>
</p>
<em>Returns:</em> True if any bytes are available otherwise false.</p>
<p>If no bytes are immediately available, the process sleeps for up to the given number of milliseconds, returning true immediately any bytes become available or false if the period expires without any bytes becoming available.
It only takes a few µsecs to return false if no bytes are available and no wait time has been requested.</p>
</p>
<p><em>Returns:</em> True if any bytes are available otherwise false.
</p>
<p>It only takes a few µsecs to return false if no bytes are available and no wait time has been requested.
</p>
</td></tr>
</td></tr>
<tr><td>if</td><td>var().eof()</td><td>True if stdin is at end of file</p>
<tr><td>if</td><td>var().eof()</td><td><p>True if stdin is at end of file
</p>
</td></tr>
</td></tr>
<tr><td>if</td><td>var().echo(on_off = true)</td><td>Sets terminal echo on or off.</p>
<tr><td>if</td><td>var().echo(on_off = true)</td><td><p>Sets terminal echo on or off.
"On" causes all stdin data to be reflected to stdout if stdin is a terminal.</p>
</p>
Turning terminal echo off can be used to prevent display of confidential information.</p>
<p>"On" causes all stdin data to be reflected to stdout if stdin is a terminal.
<em>Returns:</em> True if successful.</p>
</p>
<p>Turning terminal echo off can be used to prevent display of confidential information.
</p>
<p><em>Returns:</em> True if successful.
</p>
</td></tr>
</td></tr>
<tr><td></td><td>var().breakon()</td><td>Install various interrupt handlers.</p>
<tr><td></td><td>var().breakon()</td><td><p>Install various interrupt handlers.
Automatically called in program/thread initialisation by exodus_main.</p>
</p>
SIGINT - Ctrl+C -> "Interrupted. (C)ontinue (Q)uit (B)acktrace (D)ebug (A)bort ?"</p>
<p>Automatically called in program/thread initialisation by exodus_main.
SIGHUP - Sets a variable "RELOAD_req" which may be handled or ignored by the program.</p>
</p>
SIGTERM - Sets a variable "TERMINATE_req" which may be handled or ignored by the program.</p>
<p>SIGINT - Ctrl+C -> "Interrupted. (C)ontinue (Q)uit (B)acktrace (D)ebug (A)bort ?"
</p>
<p>SIGHUP - Sets a variable "RELOAD_req" which may be handled or ignored by the program.
</p>
<p>SIGTERM - Sets a variable "TERMINATE_req" which may be handled or ignored by the program.
</p>
</td></tr>
</td></tr>
<tr><td></td><td>var().breakoff()</td><td>Disable keyboard interrupt.</p>
<tr><td></td><td>var().breakoff()</td><td><p>Disable keyboard interrupt.
Ctrl+C becomes inactive in terminal.</p>
</p>
<p>Ctrl+C becomes inactive in terminal.
</p>
</td></tr>
</td></tr>
</table>
</table>
Line 2,708: Line 3,324:


</td></tr>
</td></tr>
<tr><td></td><td>varnum.initrnd()</td><td>Initialise the seed for rnd()</p>
<tr><td></td><td>varnum.initrnd()</td><td><p>Initialise the seed for rnd()
Allows the stream of pseudo random numbers generated by rnd() to be reproduced.</p>
</p>
<p>Allows the stream of pseudo random numbers generated by rnd() to be reproduced.
</p>
Seeded from std::chrono::high_resolution_clock::now() if the argument is 0;
Seeded from std::chrono::high_resolution_clock::now() if the argument is 0;


Line 2,717: Line 3,335:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.rnd()</td><td>Pseudo random number generator</p>
<tr><td>var=</td><td>varnum.rnd()</td><td><p>Pseudo random number generator
<em>Returns:</em> a pseudo random integer between 0 and the provided maximum minus 1.</p>
</p>
<p><em>Returns:</em> a pseudo random integer between 0 and the provided maximum minus 1.
</p>
Uses std::mt19937 and std::uniform_int_distribution<int>
Uses std::mt19937 and std::uniform_int_distribution<int>


Line 2,768: Line 3,388:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.loge()</td><td>Natural logarithm</p>
<tr><td>var=</td><td>varnum.loge()</td><td><p>Natural logarithm
</p>
<em>Returns:</em> Floating point ver (double)
<em>Returns:</em> Floating point ver (double)


Line 2,776: Line 3,397:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.integer()</td><td>Truncate decimal numbers towards zero</p>
<tr><td>var=</td><td>varnum.integer()</td><td><p>Truncate decimal numbers towards zero
</p>
<em>Returns:</em> An integer var
<em>Returns:</em> An integer var


Line 2,788: Line 3,410:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.floor()</td><td>Truncate decimal numbers towards negative</p>
<tr><td>var=</td><td>varnum.floor()</td><td><p>Truncate decimal numbers towards negative
</p>
<em>Returns:</em> An integer var
<em>Returns:</em> An integer var


Line 2,800: Line 3,423:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.mod(modulus)</td><td>Modulus function</p>
<tr><td>var=</td><td>varnum.mod(modulus)</td><td><p>Modulus function
Identical to C++ % operator only for positive numbers and modulus</p>
</p>
Negative denominators are considered as periodic with positiive numbers</p>
<p>Identical to C++ % operator only for positive numbers and modulus
Result is between [0, modulus) if modulus is positive</p>
</p>
Result is between (modulus, 0] if modulus is negative (symmetric)</p>
<p>Negative denominators are considered as periodic with positiive numbers
<em>Throws:</em> VarDivideByZero if modulus is zero.</p>
</p>
<p>Result is between [0, modulus) if modulus is positive
</p>
<p>Result is between (modulus, 0] if modulus is negative (symmetric)
</p>
<p><em>Throws:</em> VarDivideByZero if modulus is zero.
</p>
Floating point works.
Floating point works.


Line 2,816: Line 3,445:


</td></tr>
</td></tr>
<tr><td>int=</td><td>var::setprecision(newprecision)</td><td>Set the maximum floating point precision.</p>
<tr><td>int=</td><td>var::setprecision(newprecision)</td><td><p>Set the maximum floating point precision.
This is the number of post-decimal point digits to consider for floating point comparison and implicit conversion to strings.</p>
</p>
The default precision is 4 which is 0.0001.</p>
<p>This is the number of post-decimal point digits to consider for floating point comparison and implicit conversion to strings.
NUMBERS AND DIFFERENCES SMALLER THAN 0.0001 ARE TREATED AS ZERO UNLESS PRECISION IS INCREASED.</p>
</p>
<em>newprecision:</em> New precision between -307 and 308 inclusive.</p>
<p>The default precision is 4 which is 0.0001.
<em>Returns:</em> The new precision if successful or the old precision if not.</p>
</p>
Not required if using common numbers or using the explicit rounding and formatting functions to convert numbers to strings.</p>
<p>NUMBERS AND DIFFERENCES SMALLER THAN 0.0001 ARE TREATED AS ZERO UNLESS PRECISION IS INCREASED.
Increasing the precision allows comparing and outputting smaller numbers but creates errors handling large numbers.</p>
</p>
Setting precision inside a perform, execute or dictionary function lasts until termination of the function.</p>
<p><em>newprecision:</em> New precision between -307 and 308 inclusive.
</p>
<p><em>Returns:</em> The new precision if successful or the old precision if not.
</p>
<p>Not required if using common numbers or using the explicit rounding and formatting functions to convert numbers to strings.
</p>
<p>Increasing the precision allows comparing and outputting smaller numbers but creates errors handling large numbers.
</p>
<p>Setting precision inside a perform, execute or dictionary function lasts until termination of the function.
</p>
See cli/demo_precision for more info.
See cli/demo_precision for more info.


Line 2,834: Line 3,472:


</td></tr>
</td></tr>
<tr><td>int=</td><td>var::getprecision()</td><td>Returns: The current precision setting.</p>
<tr><td>int=</td><td>var::getprecision()</td><td>
<p><em>Returns:</em> The current precision setting.
</p>
See setprecision() for more info.
See setprecision() for more info.


Line 2,847: Line 3,487:
<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>vardate.oconv("D")</td><td>Date output: Convert internal date format to human readable date or calendar info in text format.</p>
<tr><td>var=</td><td>vardate.oconv("D")</td><td><p>Date output: Convert internal date format to human readable date or calendar info in text format.
<em>Returns:</em> Human readable date or calendar info, or the original value unconverted if non-numeric.</p>
</p>
<em>Flags:</em> See examples below.</p>
<p><em>Returns:</em> Human readable date or calendar info, or the original value unconverted if non-numeric.
</p>
<p><em>Flags:</em> See examples below.
</p>
Any Dynamic array structure is preserved.
Any Dynamic array structure is preserved.


Line 2,889: Line 3,532:


  // or
  // or
  v2 =  oconv(v3, "D"  ) ; //  "18 OCT 2001"  </code></pre>
  v2 =  oconv(v3, "D"  ) ;</code></pre>
 
</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.iconv("D")</td><td>Date input: Convert human readable date to internal date format.</p>
<tr><td>var=</td><td>varstr.iconv("D")</td><td><p>Date input: Convert human readable date to internal date format.
<em>Returns:</em> Internal date or "" if the input is an invalid date.</p>
</p>
Internal date format is whole days since 1967-12-31 00:00:00 which is day 0.</p>
<p><em>Returns:</em> Internal date or "" if the input is an invalid date.
</p>
<p>Internal date format is whole days since 1967-12-31 00:00:00 which is day 0.
</p>
Any Dynamic array structure is preserved.
Any Dynamic array structure is preserved.


Line 2,924: Line 3,571:


</td></tr>
</td></tr>
<tr><td>var=</td><td>vartime.oconv("MT")</td><td>Time output: Convert internal time format to human readable time e.g. "10:30:59".</p>
<tr><td>var=</td><td>vartime.oconv("MT")</td><td><p>Time output: Convert internal time format to human readable time e.g. "10:30:59".
<em>Returns:</em> Human readable time or the original value unconverted if non-numeric.</p>
</p>
Conversion code (e.g. "MTHS") is "MT" + flags ...</p>
<p><em>Returns:</em> Human readable time or the original value unconverted if non-numeric.
<em>Flags:</em></p>
</p>
"H" - Show AM/PM otherwise 24 hour clock is used.</p>
<p>Conversion code (e.g. "MTHS") is "MT" + flags ...
"S" - Output seconds</p>
</p>
"2" = Ignored (used in iconv)</p>
<p><em>Flags:</em>
":" - Any other flag is used as the separator char instead of ":"</p>
</p>
<p>"H" - Show AM/PM otherwise 24 hour clock is used.
</p>
<p>"S" - Output seconds
</p>
<p>"2" = Ignored (used in iconv)
</p>
<p>":" - Any other flag is used as the separator char instead of ":"
</p>
Any Dynamic array structure is preserved.
Any Dynamic array structure is preserved.


Line 2,955: Line 3,610:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.iconv("MT")</td><td>Time input: Convert human readable time (e.g. "10:30:59") to internal time format.</p>
<tr><td>var=</td><td>varstr.iconv("MT")</td><td><p>Time input: Convert human readable time (e.g. "10:30:59") to internal time format.
<em>Returns:</em> Internal time or "" if the input is an invalid time.</p>
</p>
Internal time format is whole seconds since midnight.</p>
<p><em>Returns:</em> Internal time or "" if the input is an invalid time.
<em>Accepts:</em> Two or three groups of digits surrounded and separated by any non-digits char(s).</p>
</p>
<p>Internal time format is whole seconds since midnight.
</p>
<p><em>Accepts:</em> Two or three groups of digits surrounded and separated by any non-digits char(s).
</p>
Any Dynamic array structure is preserved.
Any Dynamic array structure is preserved.


Line 2,980: Line 3,639:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.oconv("MD")</td><td>Number output: Convert internal numbers to external text format after rounding and optional scaling.</p>
<tr><td>var=</td><td>varnum.oconv("MD")</td><td><p>Number output: Convert internal numbers to external text format after rounding and optional scaling.
<em>Returns:</em> A string or, if the value is not numeric, then no conversion is performed and the original value is returned.</p>
</p>
Conversion code (e.g. "MD20") is "MD" or "MC", 1st digit, 2nd digit, flags ...</p>
<p><em>Returns:</em> A string or, if the value is not numeric, then no conversion is performed and the original value is returned.
</p>
</p>
MD outputs like 123.45 (International)</p>
<p>Conversion code (e.g. "MD20") is "MD" or "MC", 1st digit, 2nd digit, flags ...
MC outputs like 123,45 (European)</p>
</p>
</p>
1st digit = Decimal places to display. Also decimal places to move if 2nd digit not present and no P flag present.</p>
 
2nd digit = Optional decimal places to move left if P flag not present.</p>
<p>MD outputs like 123.45 (International)
</p>
</p>
<em>Flags:</em></p>
<p>MC outputs like 123,45 (European)
"P" - Preserve decimal places. Same as 2nd digit = 0;</p>
"Z" - Zero flag - return "" if zero.</p>
"X" - No conversion - return as is.</p>
"." or "," - Separate thousands depending on MD or MC.</p>
"-" means suffix negatives with "-" and positives with " " (space).</p>
"<" means wrap negatives in "<" and ">" chars.</p>
"C" means suffix negatives with "CR" and positives or zero with "DB".</p>
"D" means suffix negatives with "DB" and positives or zero with "CR".</p>
</p>
</p>
  Any Dynamic array structure is preserved.
 
<p>1st digit = Decimal places to display. Also decimal places to move if 2nd digit not present and no P flag present.
</p>
<p>2nd digit = Optional decimal places to move left if P flag not present.
</p>
 
<p><em>Flags:</em>
</p>
<p>"P" - Preserve decimal places. Same as 2nd digit = 0;
</p>
<p>"Z" - Zero flag - return "" if zero.
</p>
<p>"X" - No conversion - return as is.
</p>
<p>"." or "," - Separate thousands depending on MD or MC.
</p>
<p>"-" means suffix negatives with "-" and positives with " " (space).
</p>
<p>"<" means wrap negatives in "<" and ">" chars.
</p>
<p>"C" means suffix negatives with "CR" and positives or zero with "DB".
</p>
<p>"D" means suffix negatives with "DB" and positives or zero with "CR".
</p>
 
  Any Dynamic array structure is preserved.


<pre><code class='hljs-ncdecl language-javascript'>var v1 = -1234.567;
<pre><code class='hljs-ncdecl language-javascript'>var v1 = -1234.567;
Line 3,019: Line 3,694:
v2 =  oconv(v1, "MD20"  ) ; //  "-1234.57"  </code></pre>
v2 =  oconv(v1, "MD20"  ) ; //  "-1234.57"  </code></pre>
</td></tr>
</td></tr>
<tr><td>var=</td><td>var.oconv("LRC")</td><td>Text justification: Left, right and center. Padding and truncating. See Procrustes.</p>
<tr><td>var=</td><td>var.oconv("LRC")</td><td><p>Text justification: Left, right and center. Padding and truncating. See Procrustes.
e.g. "L#10", "R#10", "C#10"</p>
</p>
Useful when outputting to terminal devices where spaces are used for alignment.</p>
<p>e.g. "L#10", "R#10", "C#10"
Dynamic array structure is preserved.</p>
</p>
<p>Useful when outputting to terminal devices where spaces are used for alignment.
</p>
<p>Dynamic array structure is preserved.
</p>
ASCII only.
ASCII only.


Line 3,049: Line 3,728:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.oconv("T")</td><td>Text folding and justification.</p>
<tr><td>var=</td><td>varstr.oconv("T")</td><td><p>Text folding and justification.
e.g. T#20</p>
</p>
Useful when outputting to terminal devices where spaces are used for alignment.</p>
<p>e.g. T#20
Splits text into multiple fixed length lines by inserting spaces and TM chars.</p>
</p>
<p>Useful when outputting to terminal devices where spaces are used for alignment.
</p>
<p>Splits text into multiple fixed length lines by inserting spaces and TM chars.
</p>
ASCII only.
ASCII only.


Line 3,061: Line 3,744:


</td></tr>
</td></tr>
<tr><td>expr</td><td>varnum.oconv("MR")</td><td>Character replacement</p>
<tr><td>expr</td><td>varnum.oconv("MR")</td><td><p>Character replacement
</p>
e.g. MRU
e.g. MRU


Line 3,077: Line 3,761:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.oconv("HEX")</td><td>Convert the chars of a string to a string of pairs of hexadecimal digits.</p>
<tr><td>var=</td><td>varstr.oconv("HEX")</td><td><p>Convert the chars of a string to a string of pairs of hexadecimal digits.
<em>varstr:</em> A string. Numbers will be converted to strings for conversion. 1.2 -> "1.2" -> hex "312E32"</p>
</p>
Dynamic array structure is not preserved. Field marks are converted to HEX as for all other bytes.</p>
<p><em>varstr:</em> A string. Numbers will be converted to strings for conversion. 1.2 -> "1.2" -> hex "312E32"
The size of the output is always precisely double that of the input.</p>
</p>
<p>Dynamic array structure is not preserved. Field marks are converted to HEX as for all other bytes.
</p>
<p>The size of the output is always precisely double that of the input.
</p>
This function is the exact inverse of iconv("HEX").
This function is the exact inverse of iconv("HEX").


Line 3,093: Line 3,781:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.iconv("HEX")</td><td>Convert a string of pairs of hexadecimal digits to a string of chars.</p>
<tr><td>var=</td><td>varstr.iconv("HEX")</td><td><p>Convert a string of pairs of hexadecimal digits to a string of chars.
<em>varstr:</em> Must be a string of only hex digits 0-9, a-f or A-F.</p>
</p>
<em>Returns:</em> A string if all input was hex digits otherwise "".</p>
<p><em>varstr:</em> Must be a string of only hex digits 0-9, a-f or A-F.
Dynamic array structure is not preserved. Any field marks prevent conversion.</p>
</p>
This function is the exact inverse of oconv("HEX").</p>
<p><em>Returns:</em> A string if all input was hex digits otherwise "".
After prefixing a "0" to an odd sized input, the size of the output is always precisely half that of the input.</p>
</p>
<p>Dynamic array structure is not preserved. Any field marks prevent conversion.
</p>
<p>This function is the exact inverse of oconv("HEX").
</p>
<p>After prefixing a "0" to an odd sized input, the size of the output is always precisely half that of the input.
</p>
</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.oconv("MX")</td><td>Convert number to hexadecimal string.</p>
<tr><td>var=</td><td>varnum.oconv("MX")</td><td><p>Convert number to hexadecimal string.
"MX":  Convert and trim leading zeros                      e.g. oconv(1025, "MX")  -> "401"</p>
</p>
"MXn":  Pad with up to n leading zeros but do not truncate. e.g. oconv(1025, "MX8") -> "00000401"</p>
<p>"MX":  Convert and trim leading zeros                      e.g. oconv(1025, "MX")  -> "401"
"MXnT": Pad and truncate to n characters.                  e.g. oconv(1025, "MX2") -> "01"</p>
</p>
"n":    Width. 0-9, A-G = 10 - 16.</p>
<p>"MXn":  Pad with up to n leading zeros but do not truncate. e.g. oconv(1025, "MX8") -> "00000401"
<em>varnum:</em> A number or dynamic array of numbers. Floating point numbers are rounded to integers before conversion.</p>
</p>
<em>Returns:</em> A string of hexadecimal digits or a dynamic array of the same. Elements that are not numeric are left untouched and unconverted.</p>
<p>"MXnT": Pad and truncate to n characters.                  e.g. oconv(1025, "MX2") -> "01"
Dynamic array structure is preserved.</p>
</p>
Negative numbers are treated as unsigned 8 byte integers (uint64).</p>
<p>"n":    Width. 0-9, A-G = 10 - 16.
0  -> "00"</p>
</p>
1  -> "01"</p>
<p><em>varnum:</em> A number or dynamic array of numbers. Floating point numbers are rounded to integers before conversion.
15 -> "0F"</p>
</p>
-1 -> "FFFF" "FFFF" "FFFF" "FFFF" (8 x "FF")</p>
<p><em>Returns:</em> A string of hexadecimal digits or a dynamic array of the same. Elements that are not numeric are left untouched and unconverted.
This function is a near inverse of iconv("MX").
</p>
 
<p>Dynamic array structure is preserved.
<pre><code class='hljs-ncdecl language-javascript'>let v1 = var("14.5]QQ]65535").oconv("MX"); // "F]QQ]FFFF"_var
</p>
<p>Negative numbers are treated as unsigned 8 byte integers (uint64).
</p>
<p>0  -> "00"
</p>
<p>1  -> "01"
</p>
<p>15 -> "0F"
</p>
<p>-1 -> "FFFF" "FFFF" "FFFF" "FFFF" (8 x "FF")
</p>
This function is a near inverse of iconv("MX").
 
<pre><code class='hljs-ncdecl language-javascript'>let v1 = "14.5]QQ]65535"_var.oconv("MX"); // "F]QQ]FFFF"_var
// or
// or
let v2 = oconv("14.5]QQ]65535"_var, "MX");</code></pre>
let v2 = oconv("14.5]QQ]65535"_var, "MX");</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.iconv("MX")</td><td>Convert hexadecimal string to number.</p>
<tr><td>var=</td><td>varstr.iconv("MX")</td><td><p>Convert hexadecimal string to number.
<em>varstr:</em> A string or dynamic array of up to 16 hex digits: 0-9, a-f, A-F.</p>
</p>
<em>Returns:</em> An integer or dynamic array of integers. Invalid elements are converted to "".</p>
<p><em>varstr:</em> A string or dynamic array of up to 16 hex digits: 0-9, a-f, A-F.
Dynamic array structure is preserved.</p>
</p>
Hex strings are converted to unsigned 8 byte integers (uint64)</p>
<p><em>Returns:</em> An integer or dynamic array of integers. Invalid elements are converted to "".
Leading zeros are ignored.</p>
</p>
"0" -> 0</p>
<p>Dynamic array structure is preserved.
"00" -> 0</p>
</p>
"1" -> 1</p>
<p>Hex strings are converted to unsigned 8 byte integers (uint64)
Hex "FFFFFFFFFFFFFFFF" (8 x "FF") -> -1.</p>
</p>
Hex "7FFFFFFFFFFFFFFF" is the maximum positive integer: 9223372036854775805.</p>
<p>Leading zeros are ignored.
Hex "8000000000000000" is the maximum negative integer: -9223372036854775808.</p>
</p>
<p>"0" -> 0
</p>
<p>"00"-> 0
</p>
<p>"1" -> 1
</p>
<p>Hex "FFFFFFFFFFFFFFFF" (8 x "FF") -> -1.
</p>
<p>Hex "7FFFFFFFFFFFFFFF" is the maximum positive integer: 9223372036854775805.
</p>
<p>Hex "8000000000000000" is the maximum negative integer: -9223372036854775808.
</p>
This function is the exact inverse of oconv("MX").
This function is the exact inverse of oconv("MX").


Line 3,139: Line 3,858:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varnum.oconv("MB")</td><td>Number to binary format: Convert number to strings of 1s and 0s</p>
<tr><td>var=</td><td>varnum.oconv("MB")</td><td><p>Number to binary format: Convert number to strings of 1s and 0s
</p>
<em>varnum:</em> If not numeric then no conversion is performed and the original value is returned.
<em>varnum:</em> If not numeric then no conversion is performed and the original value is returned.


Line 3,147: Line 3,867:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.oconv("TX")</td><td>Convert dynamic arrays to standard text format.</p>
<tr><td>var=</td><td>varstr.oconv("TX")</td><td><p>Convert dynamic arrays to standard text format.
Useful for using text editors on dynamic arrays.</p>
</p>
FMs -> \n after escaping any embedded NL</p>
<p>Useful for using text editors on dynamic arrays.
VMs -> literal "\" \n</p>
</p>
SMs -> literal "\\" \n</p>
<p>FMs -> \n after escaping any embedded NL
</p>
<p>VMs -> literal "\" \n
</p>
<p>SMs -> literal "\\" \n
</p>
etc.
etc.


Line 3,170: Line 3,895:


// 6. SM -> "\\" \n
// 6. SM -> "\\" \n
let v6 = "s1}s1"_var.oconv("TX");  // "s2" _BS _BS _NL "s2"
let v6 = "s1}s2"_var.oconv("TX");  // "s1" _BS _BS _NL "s2"


// 7. TM -> "\\\" \n
// 7. TM -> "\\\" \n
Line 3,179: Line 3,904:


</td></tr>
</td></tr>
<tr><td>var=</td><td>varstr.iconv("TX")</td><td>Convert standard text format to dynamic array.</p>
<tr><td>var=</td><td>varstr.iconv("TX")</td><td><p>Convert standard text format to dynamic array.
</p>
Reverse of oconv("TX") above.</td></tr>
Reverse of oconv("TX") above.</td></tr>
</table>
</table>
Line 3,396: Line 4,122:
<h4>Contents:</h4>
<h4>Contents:</h4>
<ol>
<ol>
<li><a href=#Exodus_Program>Exodus Program</a></li>
<li><a href=#Dim_>Dim </a></li>
<li><a href=#Select_Lists>Select Lists</a></li>
<li><a href=#Dimensioned_Array_Construction_>Dimensioned Array Construction </a></li>
<li><a href=#Perform/Execute>Perform/Execute</a></li>
<li><a href=#Array_Access>Array Access</a></li>
<li><a href=#Program_Termination_>Program Termination </a></li>
<li><a href=#Array_Mutation>Array Mutation</a></li>
<li><a href=#DB_File_Dictionaries>DB File Dictionaries</a></li>
<li><a href=#Array_Conversion>Array Conversion</a></li>
<li><a href=#I/O_Conversion>I/O Conversion</a></li>
<li><a href=#Array_DB_I/O>Array DB I/O</a></li>
<li><a href=#Ioconv_Date/Time_>Ioconv Date/Time </a></li>
<li><a href=#Array_OS_I/O>Array OS I/O</a></li>
<li><a href=#Time/Date_Utilities>Time/Date Utilities</a></li>
<li><a href=#Terminal_I/O_Utilities>Terminal I/O Utilities</a></li>
<li><a href=#Array_Utilities>Array Utilities</a></li>
<li><a href=#Record_Locking>Record Locking</a></li>


</ol>
</ol>
Line 3,412: Line 4,134:




<h4 id=Exodus_Program>Exodus Program</h4>
<h4 id=Dim_>Dim </h4>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
</table>
</table>
<h5 id=Select_Lists>Select Lists</h5>
<h5 id=Dimensioned_Array_Construction_>Dimensioned Array Construction </h5>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>select(sortselectclause_or_filehandle = "")</td><td>Create an active select list using a natural language sort/select command.</p>
<tr><td></td><td>dim d1;</td><td>Create an undimensioned array of vars pending actual dimensions.
This and all the following exoprog member functions work on an environment variable CURSOR.</p>
Identical functions are available directly on plain var objects but vars have less functionality regarding dictionaries and environment variables which are built-in to exoprog.</p>
<em>Returns:</em> True if an active select list was created, false otherwise.</p>
In the following examples, various environment variables like RECORD, ID and MV are used instead of declaring and using named vars. In actual code, either may be freely used.


<pre><code class='hljs-ncdecl language-javascript'>select("xo_clients by name by type with type 'A' 'B' and with balance between 0 and 2000");
<pre><code class='hljs-ncdecl language-javascript'>dim d1;</code></pre>
if (readnext(ID)) ... ok</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>selectkeys(keys)</td><td>Create an active select list from some given keys.
<tr><td></td><td>dim d1(nrows, ncols = 1);</td><td>Create an array of vars with a fixed number of columns and rows. All vars are unassigned.


<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001^JB001^JB002"_var);
<pre><code class='hljs-ncdecl language-javascript'>dim d1(10);
if (readnext(ID)) ... ok // ID -> "SB001"</code></pre>
dim d2(10, 3);</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>hasnext()</td><td>Check if a select list is active.
<tr><td></td><td>dim d1 = d2; // Copy</td><td>Create a copy of an array.


<pre><code class='hljs-ncdecl language-javascript'>if (hasnext()) ... ok</code></pre>
<pre><code class='hljs-ncdecl language-javascript'> dim d1 = {2, 4, 6, 8};
dim d2 = d1;</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>readnext(out key)</td><td>Get the next key from an active select list.</p>
<tr><td></td><td>dim d1 = dim(); // Move</td><td><p>Save an array created elsewhere.
<em>key:</em> [out] A string. Typically the key of a db file record.</p>
</p>
<em>Returns:</em> True if an active select list was available and the next key in the list was obtained.
Uses C++ "move" semantics.


<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001^JB001^JB002"_var);
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "f1^f2^f3"_var.split();</code></pre>
if (readnext(ID)) ... ok // ID -> "SB001"</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>readnext(out key, out valueno)</td><td>Get the next key and value number pair from an active select list.</p>
<tr><td></td><td>dim d1 = {"a", "b", "c" ...}; // Initializer list</td><td>Create an array from a list. All elements must be the same type, var, string, double, int, etc.. but all end up as vars which are a flexible type.
<em>key:</em> [out] A string. Typically the key of a db file record.</p>
<em>valueno:</em> [out] Is only available in select lists that have been created by sort/select commands that refer to multi-valued db dictionary fields where db records have multiple values for a specific field. In this case, a record key will appear multiple times in the select list since each multivalue is exploded for the purpose of sorting and selecting. This can be viewed as a process of "normalising" multivalues so they appear as multiple records instead of being held in a single record.</p>
<em>Returns:</em> True if an active select list was available and the next key in the list was obtained.


<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001]2^SB001]1^JB001]2"_var);
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = {1, 2, 3, 4, 5};
if (readnext(ID, MV)) ... ok // ID -> "SB001" // MV -> 2</code></pre>
dim d2 = {"A", "B", "C"};</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>readnext(out record, out key, out valueno)</td><td>Get the next record, key and value no from an active select list.</p>
<tr><td></td><td>dim d1 = v1;</td><td>Initialise all elements of an array to some single value or constant. A var, "", 0 etc.
<em>record:</em> [out] Is only available in select lists that have been created with the final (R) option. Otherwise the record will be returned as an empty string and must be obtained using a db read() function.</p>
<em>key:</em> [out] A string. Typically the key of a db file record.</p>
<em>valueno:</em> [out] Is only available in select lists that have been created by sort/select commands that refer to multi-valued db dictionary fields where db records have multiple values for a specific field.</p>
<em>Returns:</em> True if an active select list was available and the next key in the list was obtained.


<pre><code class='hljs-ncdecl language-javascript'>select("xo_clients by name (R)");
<pre><code class='hljs-ncdecl language-javascript'>dim d1(10);
if (readnext(RECORD, ID, MV)) ... ok;
d1 = "";</code></pre>
assert(not RECORD.empty());</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>pushselect(out cursor)</td><td>Saves a pointer to the currently active select list.</p>
<tr><td></td><td>d1.redim(nrows, ncols = 1)</td><td><p>Resize an array to a different number of rows and columns.
This allows another select list to be activated and used temporarily before the original select list is reactivated.</p>
</p>
<em>cursor:</em> [out] A var that can be passed later on to the popselect() function to reactivate the saved list.
<p>Existing data will be retained as far as possible. Any additional elements are unassigned.
</p>
<p>Resizing rows to 0 clears all data.
</p>
Resizing cols to 0 clears all data and changes its status to "undimensioned".


<pre><code class='hljs-ncdecl language-javascript'>select("xo_clients by name");
<pre><code class='hljs-ncdecl language-javascript'>dim d1;
var saved_xo_clients_cursor;
d1.redim(10, 3);</code></pre>
pushselect(saved_xo_clients_cursor);
//
// ... work with another select list ...
//
popselect(saved_xo_clients_cursor); // Reactivate the original select list.</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>popselect(cursor)</td><td>Re-establish an active select list saved by pushselect().</p>
<tr><td></td><td>d1.swap(d2) </td><td><p>Swap one array with another.
<em>cursor:</em> A var created by the pushselect() function.</p>
</p>
See pushselect() for more info.</td></tr>
Either or both may be undimensioned.
<tr><td></td><td>clearselect()</td><td>Deactivate an active select list.</p>
If no select list is active then nothing is done.


<pre><code class='hljs-ncdecl language-javascript'>clearselect();</code></pre>
<pre><code class='hljs-ncdecl language-javascript'>dim d1(5);
dim d2(10);
d1.swap(d2);</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>deleterecord(filename)</td><td>Use an active select list to delete db records.</p>
</table>
<em>Returns:</em> False if any records could not be deleted.</p>
<h5 id=Array_Access>Array Access</h5>
Contrast this function with the two argument "deleterecord(file, key)" function that deletes a single record.


<pre><code class='hljs-ncdecl language-javascript'>if (select("xo_clients with type 'Q' and with balance between 0 and 100")) {
<table class=wikitable>
  if (deleterecord("xo_clients")) ...
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
}</code></pre>
<tr><td></td><td>var v1 = d1[rowno];</br>d1[rowno] = v1;</td><td>Access and update elements of a one dimensional array using [] brackets
 
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = {1, 2, 3, 4, 5};
d1[3] = "X";
let v1 = d1[3]; // "X"</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>deleterecord(dbfile, key)</td><td>Delete a single database file record.
<tr><td></td><td>var v1 = d1[rowno, colno];</br>d1[rowno, colno] = v1;</td><td>Access and update elements of an two dimensional array using [] brackets


<pre><code class='hljs-ncdecl language-javascript'>let file = "xo_clients", key = "QQ001";
<pre><code class='hljs-ncdecl language-javascript'>dim d1(10, 5);
write("" on file, key);
d1 = "";
if (not deleterecord(file, key)) ...
d1[3, 4] = "X";
// or
let v1 = d1[3, 4]; // "X"</code></pre>
write("" on file, key);
if (not file.deleterecord(key)) ...</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>savelist(listname)</td><td>Save a currently active select list under a given name.</p>
<tr><td>var=</td><td>d1.rows()</td><td><p>Get the number of rows in the dimensioned array
After saving, the list is no longer active and hasnext() will return false.</p>
</p>
<em>Returns:</em> True if an active select list was saved, false if there was no active select list.</p>
<em>Returns:</em> A count. Can be zero, indicating an empty array.
Lists are saved as a record in the "lists" file.


<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001^SB002"_var);
<pre><code class='hljs-ncdecl language-javascript'>dim d1(5,3);
if (not savelist("my_list")) ...</code></pre>
let v1 = d1.rows(); // 5</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>getlist(listname)</td><td>Reactivate a saved select list of a given name.</p>
<tr><td>var=</td><td>d1.cols()</td><td><p>Get the number of columns in the dimensioned array
A saved list is obtained from the "lists" file and activated.</p>
</p>
<em>Returns:</em> True if an active select list was successfully reactivated, otherwise false.
<em>Returns:</em> A count.  0 if the array is undimensioned.


<pre><code class='hljs-ncdecl language-javascript'>if (not getlist("my_list")) ...</code></pre>
<pre><code class='hljs-ncdecl language-javascript'>dim d1(5,3);
let v1 = d1.cols(); // 3</code></pre>


</td></tr>
</td></tr>
<tr><td>if</td><td>deletelist(listname)</td><td>Remove a saved select list by name.</p>
<tr><td>var=</td><td>d1.join(delimiter = FM)</td><td><p>Joins all elements into a single delimited string
A saved list is deleted from the "lists" file.
</p>
<p><em>delimiter:</em> Default is FM.
</p>
<em>Returns:</em> A string var.


<pre><code class='hljs-ncdecl language-javascript'>if (not deletelist("my_list")) ...</code></pre>
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = {"f1", "f2", "f3"};
let v1 = d1.join(); // "f1^f2^f3"_var</code></pre>


</td></tr>
</td></tr>
</table>
</table>
<h5 id=Perform/Execute>Perform/Execute</h5>
<h5 id=Array_Mutation>Array Mutation</h5>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>perform(command_line)</td><td>Run an exodus program/library's main function using a command like syntax similar to that of executable programs.</p>
<tr><td></td><td>d1.splitter(str1, delimiter = FM)</td><td><p>Creates or updates the array from a given string.
A "command line" is passed to the program/library in the usual COMMAND, SENTENCE and OPTIONS environment variables instead of function arguments.</p>
</p>
The program/library's main function should have zero arguments. Performing a program/library function with main arguments results in them being unassigned and in some case core dump may occur.</p>
<p>If the dim array is undimensioned it will be dimensioned with the number of elements that the string has fields.
The following environment variables are initialised on entry to the main function of the program/library. They are preserved untouched in the calling program.</p>
</p>
SENTENCE, COMMAND, OPTIONS: Initialised from the argument "command_line".</p>
<p>If the dim array is dimensioned and has more elements than there are fields in the string, the excess array elements are initialised to "". If the record has more fields than there are elements in the array, the excess fields are all left unsplit in the final element of the array.
RECUR0, RECUR1, RECUR2, RECUR3, RECUR4 to "".</p>
</p>
ID, RECORD, MV, DICT initialised to "".</p>
<p>Predimensioning arrays allows the efficient reuse of arrays in loops and ensures that all elements are assigned values, useful when reading records from db files.
LEVEL is incremented by one.</p>
</p>
All other environment variables are shared between the caller and callee. There is essentially only one environment in any one process or thread.</p>
Using undimensioned arrays allows the efficient handling of arrays with a very variable number of elements. e.g. os text files.
Any active select list is passed to the performed program/library and can be consumed by it. Conversely any active select list created by the performed program/library will be returned to the calling program. In other words, both the performing and the performed programs/libraries share a single active select list environment. This is different from execute() which gets its own private active select list, initially inactive.</p>
<em>command_line:</em> The first word of this argument is used as the name of the program/library to be loaded and run. command_line is used to initialise the SENTENCE, COMMAND and OPTIONS environment variables.</p>
<em>Returns:</em> Whatever var the program/library returns, or "" if it calls stop() or abort(()".</p>
The return value can be ignored and discarded without any compiler warning.</p>
Exodus program/libraries may also be called directly using conventional function calling syntax. To call an exodus program/library called progname using either the syntax "call progname(args...);" or "var v1 = progname(args...);" you must "#include <progname.h>" after the "programinit()" or "libraryinit()" lines in your program/library.</td></tr>
<tr><td>var=</td><td>execute(command_line)</td><td>Run an exodus program/library's main function.</p>
Identical to perform() but any currently active select list in the calling program/library is not accessible to the executed program/library and is preserved in the calling [program as is. Any select list created by the executed library is discarded when it terminates.</td></tr>
<tr><td></td><td>chain(command_line)</td><td>Run an exodus program/library's main function after closing the current program.</p>
Identical to perform() except that the current program closes first.</td></tr>
<tr><td>var=</td><td>libinfo(libname)</td><td>Check if a lib exists to be performed/executed or called.</td></tr>
</table>
<h5 id=Program_Termination_>Program Termination </h5>


<table class=wikitable>
<pre><code class='hljs-ncdecl language-javascript'>dim d1;
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
d1.splitter("f1^f2^f3"_var); // d1.rows() -> //// Automatically dimensioned.
<tr><td></td><td>stop(message = "")</td><td>Stop the current exodus program/library normally and return to the parent exodus program/library, or return to the operating system if none.</p>
//
Calling stop() in an exodus OS command line executable program, or in a function called from the same, will terminate the OS process with an error status of 0 which is generally considered to indicate success.</p>
dim d2(10);
Calling stop() in a performed or executed exodus program/library, or in a function called from the same, will terminate the program/library being executed and return to the exodus program that performed or executed it.</td></tr>
d2.splitter("f1^f2^f3"_var); // d2.rows() -> 10 /// Predimensioned. Excess elements become ""</code></pre>
<tr><td></td><td>abort(message = "")</td><td>Abort the current exodus program/library abnormally and return to the parent exodus program/library, or return to the operating system if none.</p>
Similar to stop() but, if terminating the OS process, then return an error status of 1 which is generally considered to be an indication of failure.</td></tr>
<tr><td></td><td>abortall(message = "")</td><td>Abort the current exodus program/library abnormally and return to the parent exodus program/library, or return to the operating system if none.</p>
Similar to abort() but, if terminating the OS process, then return an error status of 2 which is generally considered to be an indication of failure.</td></tr>
<tr><td></td><td>logoff(message = "")</td><td></td></tr>
</table>
<h5 id=DB_File_Dictionaries>DB File Dictionaries</h5>


<table class=wikitable>
</td></tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td></td><td>d1.sorter(reverse = false)</td><td><p>Sort the elements of the array in place.
<tr><td>var=</td><td>calculate(dictid)</td><td>given dictid reads dictrec from DICT file and extracts from RECORD/ID or calls library</p>
called dict+DICT function dictid not const so we can mess with the library?</td></tr>
<tr><td>var=</td><td>calculate(dictid, dictfile, id, record, mv = 0)</td><td></td></tr>
<tr><td>var=</td><td>xlate(filename, key, fieldno_or_name, mode)</td><td></td></tr>
</table>
<h5 id=I/O_Conversion>I/O Conversion</h5>
 
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>oconv(input, conversion)</td><td>iconv/oconv with access to exoprogram's environment variables.</p>
exoprog's iconv/oconv have the ability to call custom functions like "[funname,args...]"</p>
</p>
</p>
[NUMBER]  // built-in. See doc below.</p>
<em>reverse:</em> Defaults to false. If true, then the order is reversed.
[DATE]    // built-in. See doc below.</p>
[DATEPERIOD]  e.g. [DATEPERIOD,1] [DATEPERIOD,1,12]</p>
[DATETIME]    e.g. [DATETIME,4*,DOS] [DATETIME,4*,MTS] [DATETIME,4*]</p>
[TIME2]      e.g. [TIME2,MT] [TIME2,MTS] [TIME2,MTS48]</p>
</td></tr>
<tr><td>var=</td><td>iconv(input, conversion)</td><td></td></tr>
</table>
<h5 id=Ioconv_Date/Time_>Ioconv Date/Time </h5>


<table class=wikitable>
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "2,20,10,1"_var.split(",");
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
d1.sorter();
<tr><td>var=</td><td>iconv|oconv(var, "[DATE]")</td><td>Use iconv/oconv code "[DATE,args]" when you want date conversion to depend on the environment variable DATEFMT, particularly its American/International setting. Otherwise use ordinary "D" conversion codes directly for slightly greater performance.</p>
let v1 = d1.join(","); // "1,2,10,20"_var</code></pre>
</p>
 
<em>var:</em> [oconv] An internal date (a number).</p>
</td></tr>
<em>Returns:</em> [oconv] A readable date in text format depending on "[DATE,args]" e.g. "31 DEC 2020" "31/12/2020" "12/31/2020"</p>
<tr><td></td><td>d1.reverser()</td><td>Reverse the elements of the array in place.
<em>var:</em> [iconv] A date in text format as above.</p>
<em>Returns:</em> [iconv] An internal date (a number) or "" if the input could not be understood as a valid date.</p>
<em>args:</em> If args is empty then DATEFMT is used as the conversion code. If args starts with "D" then args is used as the conversion codes but any E option in DATEFMT is appended. If args does not start with "D" then args are appended to DATEFMT, a "Z" option is appended, and the result used as the conversion code. A "*" option is equivalent to a second "Z" option.</p>
If you are calling iconv/oconv in code and DATEFMT is adequate for your needs then pass it directly as a function argument e.g. 'var v1 = iconv|oconv(v2, DATEFORMAT);' instead of indirectly like 'var v1 = iconv|oconv(v2, "[DATE]");'.


<pre><code class='hljs-ncdecl language-javascript'>let v1 = iconv("JAN 9 2020", "D");
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "2,20,10,1"_var.split(",");
assert(oconv(v1, "[DATE]"  ) == " 9/ 1/2020");  // "D/EZ" or "[DATE,D]" equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
d1.reverser();
assert(oconv(v1, "[DATE,4]" ) == " 9/ 1/2020"); // "D4Z"  equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
let v1 = d1.join(","); // "1,10,20,2"_var</code></pre>
assert(oconv(v1, "[DATE,*4]") == "9/1/2020");   // "D4ZZ" equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)
assert(oconv(v1, "[DATE,*]" ) == "9/1/20");      // "DZZ"  equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>iconv|oconv(var, "[NUMBER]")</td><td>Use iconv/oconv "[NUMBER,args]" either when your numbers have currency or unit code suffixes or when you want number conversion to depend on the environment variable BASEFMT to determine thousands separator and decimal point. Otherwise use ordinary "MD" conversion codes directly for slightly greater performance.</p>
<tr><td></td><td>d1.shuffler()</td><td>Randomly shuffle the order of the elements of the array in place.
Formatting for numbers with optional currency code/unit suffix and is sensitive to the International or European setting in BASEFMT regarding use of commas or dots for thousands separators and decimal points.</p>
Primarily used for oconv() but can be used in reverse for iconv.</p>
<em>var:</em> A number with an optional currency code or unit suffix. e.g. "12345.67USD"</p>
<em>Returns:</em> A formatted number with thousands separated conventionally e.g. "12.345.67USD".</p>
iconv/oconv("[NUMBER]")      oconv leaves ndecimals untouched as in the input. iconv see below.</p>
iconv/oconv("[NUMBER,2]")    Specified number of decimal places</p>
iconv/oconv("[NUMBER,BASE]") Decimal places as per BASEFMT</p>
iconv/oconv("[NUMBER,*]")    Leave decimal places untouched as in the input</p>
iconv/oconv("[NUMBER,X]")    Leave decimal places untouched as in the input</p>
iconv/oconv("[NUMBER,2Z]")  Z (suppress zero) combined with any other code for oconv results in empty output "" instead of "0.00" in case of zero input.</p>
</p>
Empty input "" gives empty output "".</p>
</p>
All leading, trailing and internal spaces are removed from the input.</p>
</p>
A trailing currency or unit code is ignored and returned on output.</p>
</p>
An exodus number is an optional leading + or - followed by one or more decimal digits 0-9 with a single optional decimal point placed anywhere.</p>
</p>
If the input is non-numeric then "" is returned and STATUS set to 2. In the case of oconv with multiple fields or values each field or value is processed separately but STATUS is set to 2 if any are non-numeric.</p>
</p>
iconv removes and oconv adds thousand separator chars. The thousands separator is  "," if BASEFMT starts with "MD" or "." if it starts with "MC".</p>
</p>
<em>oconv:</em></p>
</p>
Add thousands separator chars and optionally standardise the number of decimal places.</p>
</p>
Multiple numbers in fields, values, subvalues etc. can be processed in one string.</p>
</p>
Any leading + character is preserved on output.</p>
</p>
Z suppresses zeros and returns empty string "" instead.</p>
</p>
Special format "[NUMBER,ndecs,move_ndecs]": move_ndecs causes decimal point to be shifted left if positive or right if negative.


<pre><code class='hljs-ncdecl language-javascript'>var v1 = oconv("1234.5USD", "[NUMBER,2]"); // "1,234.50USD" // Comma added and decimal places corrected.</code></pre>
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "2,20,10,1"_var.split(",");
 
d1.shuffler();
<em>iconv:</em></p>
let v1 = d1.join(","); // random</code></pre>
</p>
Remove all thousands separator chars and optionally standardise the number of decimal places.</p>
</p>
If ndecs is not specified in the "[NUMBER]" pattern then ndecs is taken from the current RECORD using dictionary code NDECS if DICT is available otherwise it uses ndecs from BASEFMT.</p>
</p>
iconv only handles a single field/value.</p>
</p>
Optional prefix of "1/" or "/" causes the reciprocal of the number to be used. e.g. "1/100" or "/100" -> "0.01".
 
<pre><code class='hljs-ncdecl language-javascript'>var v1 = iconv("1,234.5678USD", "[NUMBER]"); // "1234.57USD" // Comma removed</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>amountunit(input0, out unitx)</td><td>Split amount+currency code/unit string into number and currency code/unit.</p>
<em>var:</em> "123.45USD"</p>
<em>Returns:</em> e.g. "123.45"</p>
<em>unitx:</em> [out] e.g. "USD"</td></tr>
<tr><td>var=</td><td>amountunit(input0)</td><td></td></tr>
</table>
</table>
<h5 id=Time/Date_Utilities>Time/Date Utilities</h5>
<h5 id=Array_Conversion>Array Conversion</h5>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>timedate2()</td><td>Returns: Text of date and time in users time zone</p>
<tr><td>dim=</td><td>d1.sort(reverse = false)</td><td>Same as sorter() but returns a new array leaving the original untouched.</td></tr>
e.g. "2MAR2025 11:52AM"</p>
<tr><td>dim=</td><td>d1.reverse()</td><td>Same as reverser() but returns a new array leaving the original untouched.</td></tr>
Offset from UTC by TZ seconds.</td></tr>
<tr><td>dim=</td><td>d1.shuffle()</td><td>Same as shuffler() but returns a new array leaving the original untouched.</td></tr>
<tr><td></td><td>getdatetime(out user_date, out user_time, out system_date, out system_time, out UTC_date, out UTC_time)</td><td>Returns: User, server and UTC date and time</p>
User date and time is determined by adding the environment variable TZ.f(1)'s TZ offset (in seconds) to UTC date/time obtained from the operating system.</p>
"system" date and time is normally the same as UTC date/time and is determined by adding the environment variable TZ.f(2)'s TZ offset (in seconds) to UTC date/time obtained from the operating system.</p>
</td></tr>
<tr><td>var=</td><td>elapsedtimetext()</td><td>Get text of elapsed time since environment variable TIMESTAMP was initialised with ostimestamp() at program/thread startup.</p>
TIMESTAMP can be updated using ostimestamp() as and when desired.
 
<pre><code class='hljs-ncdecl language-javascript'>var v1 = elapsedtimetext(); // e.g. "< 1ms"</code></pre>
 
</td></tr>
<tr><td>var=</td><td>elapsedtimetext(timestamp1, timestamp2)</td><td>Get text of elapsed time between two timestamps
 
<pre><code class='hljs-ncdecl language-javascript'>let v1 = elapsedtimetext(0, 0.55);  // "13 hours, 12 mins"
let v2 = elapsedtimetext(0, 0.001); // "1 min, 26 secs"</code></pre>
 
</td></tr>
</table>
</table>
<h5 id=Terminal_I/O_Utilities>Terminal I/O Utilities</h5>
<h5 id=Array_DB_I/O>Array DB I/O</h5>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td></td><td>note(msg, options, io response)</td><td>If stdin is a terminal, output a message to stdout and optionally pause processing and request a response from the user, otherwise set the response to "" and continue.</p>
<tr><td></td><td>d1.write(dbfile, key)</td><td><p>Writes a db file record created from an array.
<em>options:</em> R = Response requested. C upper case response.
</p>
Each element in the array becomes a separate field in the db record. Any redundant trailing FMs are suppressed.


<pre><code class='hljs-ncdecl language-javascript'>var response;
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "Client GD^G^20855^30000^1001.00^20855.76539"_var.split();
// call note("Enter something", "RC", response);</code></pre>
let file = "xo_clients", key = "GD001";
if (not deleterecord("xo_clients", "GD001")) {}; // Cleanup first
d1.write(file, key);
// or
write(d1 on file, key);</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>note(msg)</td><td>Output a message to stdin and continue.
<tr><td>if</td><td>d1.read(dbfile, key)</td><td><p>Read a db file record into an array.
</p>
<p>Each field in the database record becomes a single element in the array.
</p>
<p><em>Returns:</em> True if the record exists or false if not,
</p>
<p>If the array is predimensioned then any excess array elements are initialised to "" and any excess record fields are left unsplit in the final array element. See dim splitter for more info.
</p>
If the array is not predimensioned (rows and cols = 0) then it will be dimensioned to have exactly the same number of rows as there are fields in the record being read.


<pre><code class='hljs-ncdecl language-javascript'>call note("Hello world.");</code></pre>
<pre><code class='hljs-ncdecl language-javascript'>dim d1(10);
let file = "xo_clients", key = "GD001";
if (not d1.read(file, key)) ... // d1.join() -> "Client GD^G^20855^30000^1001.00^20855.76539^^^^"_var
// or
if (not read(d1 from file, key)) ...</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>decide(question, options = "")</td><td>If stdin is a terminal, pause processing, list some given options to stdout and request the user to make a choice, otherwise set the response to "" and continue.</p>
</table>
<em>Returns:</em> The chosen option (value not number) or "" if the user cancelled.</td></tr>
<h5 id=Array_OS_I/O>Array OS I/O</h5>
<tr><td>var=</td><td>decide(question, options, out reply, defaultreply = 1)</td><td>Same as decide() above but extended.</p>
<em>defaultreply:</em> A default option if the user presses Enter.</p>
<em>reply:</em> [out] The option number that the user chose or "" if they cancelled.</td></tr>
<tr><td>if</td><td>esctoexit()</td><td>If stdin is a terminal, check if a key has been pressed and, if so, pause execution and ask the user to confirm if they want to escape/cancel or resume processing.</p>
<em>Returns:</em> True if a key has been pressed and the user confirms to escape/cancel. False if no key has been pressed or the user chooses to resume and not escape/cancel.</td></tr>
<tr><td>var=</td><td>AT(code)</td><td>Get a string to control terminal operation.</p>
<em>Returns:</em> A string to be output to the terminal in order to accomplish the desired operation.</p>
The terminal protocol is xterminal.</p>
<em>code:</em></p>
n  Position the cursor at column number n</p>
0  Position the cursor at column number 0</p>
-1  Clear the screen and home the cursor</p>
-2  Position the cursor at the top left home (x,y = 0,0)</p>
-3  Clear from the cursor at the end of screen</p>
-4  Clear from cursor to end of line</p>
-40 Position the cursor at columnno 0 and clear to end of line</td></tr>
<tr><td>var=</td><td>AT(x, y)</td><td>Get a terminal cursor positioning string.</p>
<em>Returns:</em> A string to be output to the terminal to position the cursor at the desired screen x and y position.</p>
The terminal protocol is xterminal.</td></tr>
<tr><td>if</td><td>getcursor(out cursor, delayms = 3000, max_errors = 0)</td><td>Get the position of the terminal cursor.</p>
<em>cursor:</em> [out] If stdin is a terminal, an FM delimited string containing the x and y coordinates of the current terminal cursor.</p>
If stdin is not a terminatl then an empty string "" is returned.</p>
The cursor additionally contains a third field which contains the delay in ms from the terminal.</p>
The FM delimited string returned can be later passed to setcursor() to reposition the cursor back to its original position or it can be parsed and used accordingly.</p>
<em>delayms:</em> Default 3000ms. The maximum time to wait for terminal response.</p>
<em>max_errors:</em> Default is 0. If not zero, reset the number of times to error before automatically disabling getcursor(). max_errors is initialised to 3. If negative then max_errors has the the effect of disabling all future calls to getcursor().</p>
In case the terminal fails to respond correctly within the required timeout, or is currently disabled due to too many failures, or has been specifically disabled then the returned "cursor" var contains a 4th field:</p>
TIMEOUT - The terminal failed to respond within the timeout.</p>
READ_ERROR - Failed to read terminal response.</p>
INVALID_RESPONSE - Terminal response invalid.</p>
SETUP_ERROR - Terminal setup failed.</p>
DISABLED - Terminal is disabled due to more errors than the maximum currently set.


<pre><code class='hljs-ncdecl language-javascript'>var cursor;
<table class=wikitable>
if (isterminal() and not getcursor(cursor)) ... // cursor becomes something like "0^20^0.012345"_var</code></pre>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>d1.oswrite(osfilename, codepage = "")</td><td><p>Creates an entire os text file from an array
</p>
<p>Each element of the array becomes one line in the os file delimited by \n
</p>
<p>Any existing os file is overwritten and replaced.
</p>
<p><em>codepage:</em> Optional: Data is converted from UTF8 to the required codepage/encoding before output. If the conversion cannot be performed then return false.
</p>
<em>Returns:</em> True if successful or false if not.


</td></tr>
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "aaa=1\nbbb=2\nccc=3\n"_var.split("\n");
<tr><td>var=</td><td>getcursor()</td><td>Get the position of the terminal cursor.</p>
if (not osremove("xo_conf.txt")) {}; // Cleanup first
For more info see the main getcursor() function above.
let osfilename = "xo_conf.txt";
 
if (not d1.oswrite(osfilename)) ...
<pre><code class='hljs-ncdecl language-javascript'>let cursor = getcursor(); // If isterminal() then cursor becomes something like "0^20^0.012345"_var</code></pre>
// or
if (not oswrite(d1 on osfilename)) ...</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>setcursor(cursor_coordinates)</td><td>If stdin is a terminal, position the cursor at x and y as per the given coordinates.</p>
<tr><td>if</td><td>d1.osread(osfilename, codepage = "")</td><td><p>Read an entire os text file into an array.
<em>cursor_coordinates:</em> An FM delimited string containing the x and y coordinates of the terminal cursor as can be obtained by getcursor().
</p>
 
<p>Each line in the os file, delimited by \n or \r\n, becomes a separate element in the array.
<pre><code class='hljs-ncdecl language-javascript'>if (isterminal()) {
</p>
    let cursor = getcursor(); // Save the current cursor position.
<p>Existing data in the array is lost and the array is redimensioned to the number of lines in the input data.
    TRACE(cursor)             // Show the saved cursor position.
</p>
    print(AT(0,0));          // Position the cursor at 0,0.
<p><em>codepage:</em> Optional. Data will be converted from the specified codepage/encoding to UTF8 after being read. If the conversion cannot be performed then return false.
    setcursor(cursor);        // Restore its position
</p>
}</code></pre>
<p><em>Returns:</em> True if successful or false if not.
</p>
If the first \n in the file is \r\n then the whole file will be split using \r\n as delimiter.
 
<pre><code class='hljs-ncdecl language-javascript'>dim d1;
let osfilename = "xo_conf.txt";
if (not d1.osread(osfilename)) ... // d1.join("\n") -> "aaa=1\nbbb=2\nccc=3\n"_var0
// or
if (not osread(d1 from osfilename)) ...</code></pre>
 
</td></tr>
</td></tr>
</table>
</table>
<h5 id=Array_Utilities>Array Utilities</h5>


<table class=wikitable>
</body>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
</html>
<tr><td>var=</td><td>invertarray(input, pad = false)</td><td>Dynamic array fields become values and vice versa</p>
</html>
<em>Returns:</em> The inverted dynamic array.</p>
<em>pad:</em> If true then on return, all fields will have the same number of values with superfluous trailing VMs where necessary.


<pre><code class='hljs-ncdecl language-javascript'>let v1 = "a]b]c^1]2]3"_var;
<html>
let v2 = invertarray(v1); // "a]1^b]2^c]3"_var</code></pre>
<!DOCTYPE html>
<html>
<head>
</head>
<body>


</td></tr>
<tr><td></td><td>sortarray(io array, fns = "", order = "")</td><td>Sorts fields of multivalues of dynamic arrays in parallel</p>
<em>fns:</em> VM separated list of field numbers to sort in parallel based on the first field number</p>
<em>order:</em></p>
AL Ascending  - Left Justified  - Alphabetic</p>
DL Descending - Left Justfiied  - Alphabetic</p>
AR Ascending  - Right Justified - Numeric</p>
DR Descending - Right Justified - Numeric


<pre><code class='hljs-ncdecl language-javascript'>var v1 = "f1^10]20]2]1^ww]xx]yy]zz^f3^f4"_var;  // fields 2 and 3 are parallel multivalues and currently unordered.
<!-- highlight.js for c++ syntax highlighting -->
sortarray(v1, "2]3"_var, "AR"); // v1 -> "f1^1]2]10]20^zz]yy]ww]xx^f3^f4"_var</code></pre>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
 
</td></tr>
</table>
<h5 id=Record_Locking>Record Locking</h5>
 
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>lockrecord(filename, io file, keyx, recordx, waitsecs = 0, allowduplicate = false)</td><td>Does not actually return record</td></tr>
<tr><td>if</td><td>lockrecord(filename, io file, keyx)</td><td></td></tr>
<tr><td>if</td><td>unlockrecord(filename, io file, key)</td><td></td></tr>
<tr><td>if</td><td>unlockrecord()</td><td></td></tr>
</table>
 
</body>
</html>
</html>
 
<html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
 
 
<!-- highlight.js for c++ syntax highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/cpp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/cpp.min.js"></script>
Line 4,016: Line 4,590:
<h4>Contents:</h4>
<h4>Contents:</h4>
<ol>
<ol>
<li><a href=#Dim_>Dim </a></li>
<li><a href=#Exodus_Program>Exodus Program</a></li>
<li><a href=#Dimensioned_Array_Construction_>Dimensioned Array Construction </a></li>
<li><a href=#Select_Lists>Select Lists</a></li>
<li><a href=#Array_Access>Array Access</a></li>
<li><a href=#Perform/Execute>Perform/Execute</a></li>
<li><a href=#Array_Mutation>Array Mutation</a></li>
<li><a href=#Program_Termination_>Program Termination </a></li>
<li><a href=#Array_Conversion>Array Conversion</a></li>
<li><a href=#DB_File_Dictionaries>DB File Dictionaries</a></li>
<li><a href=#Array_DB_I/O>Array DB I/O</a></li>
<li><a href=#I/O_Conversion>I/O Conversion</a></li>
<li><a href=#Array_OS_I/O>Array OS I/O</a></li>
<li><a href=#Ioconv_Date/Time_>Ioconv Date/Time </a></li>
<li><a href=#Time/Date_Utilities>Time/Date Utilities</a></li>
<li><a href=#Terminal_I/O_Utilities>Terminal I/O Utilities</a></li>
<li><a href=#Array_Utilities>Array Utilities</a></li>
<li><a href=#Record_Locking>Record Locking</a></li>


</ol>
</ol>
Line 4,028: Line 4,606:




<h4 id=Dim_>Dim </h4>
<h4 id=Exodus_Program>Exodus Program</h4>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
</table>
</table>
<h5 id=Dimensioned_Array_Construction_>Dimensioned Array Construction </h5>
<h5 id=Select_Lists>Select Lists</h5>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td></td><td>dim d1;</td><td>Create an undimensioned array of vars pending actual dimensions.
<tr><td>if</td><td>select(sortselectclause_or_filehandle = "")</td><td><p>Create an active select list using a natural language sort/select command.
</p>
<p>This and all the following exoprog member functions work on an environment variable CURSOR.
</p>
<p>Identical functions are available directly on plain var objects but vars have less functionality regarding dictionaries and environment variables which are built-in to exoprog.
</p>
<p><em>Returns:</em> True if an active select list was created, false otherwise.
</p>
In the following examples, various environment variables like RECORD, ID and MV are used instead of declaring and using named vars. In actual code, either may be freely used.


<pre><code class='hljs-ncdecl language-javascript'>dim d1;</code></pre>
<pre><code class='hljs-ncdecl language-javascript'>select("xo_clients by name by type with type 'A' 'B' and with balance between 0 and 2000");
if (readnext(ID)) ... ok</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>dim d1(nrows, ncols = 1);</td><td>Create an array of vars with a fixed number of columns and rows. All vars are unassigned.
<tr><td>if</td><td>selectkeys(keys)</td><td>Create an active select list from some given keys.


<pre><code class='hljs-ncdecl language-javascript'>dim d1(10);
<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001^JB001^JB002"_var);
dim d2(10, 3);</code></pre>
if (readnext(ID)) ... ok // ID -> "SB001"</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>dim d1 = d2; // Copy</td><td>Create a copy of an array.
<tr><td>if</td><td>hasnext()</td><td>Check if a select list is active.


<pre><code class='hljs-ncdecl language-javascript'> dim d1 = {2, 4, 6, 8};
<pre><code class='hljs-ncdecl language-javascript'>if (hasnext()) ... ok</code></pre>
dim d2 = d1;</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>dim d1 = dim(); // Move</td><td>Save an array created elsewhere.</p>
<tr><td>if</td><td>readnext(out key)</td><td><p>Get the next key from an active select list.
Uses C++ "move" semantics.
</p>
<p><em>key:</em> [out] A string. Typically the key of a db file record.
</p>
<em>Returns:</em> True if an active select list was available and the next key in the list was obtained.


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "f1^f2^f3"_var.split();</code></pre>
<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001^JB001^JB002"_var);
if (readnext(ID)) ... ok // ID -> "SB001"</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>dim d1 = {"a", "b", "c" ...}; // Initializer list</td><td>Create an array from a list. All elements must be the same type, var, string, double, int, etc.. but all end up as vars which are a flexible type.
<tr><td>if</td><td>readnext(out key, out valueno)</td><td><p>Get the next key and value number pair from an active select list.
</p>
<p><em>key:</em> [out] A string. Typically the key of a db file record.
</p>
<p><em>valueno:</em> [out] Is only available in select lists that have been created by sort/select commands that refer to multi-valued db dictionary fields where db records have multiple values for a specific field. In this case, a record key will appear multiple times in the select list since each multivalue is exploded for the purpose of sorting and selecting. This can be viewed as a process of "normalising" multivalues so they appear as multiple records instead of being held in a single record.
</p>
<em>Returns:</em> True if an active select list was available and the next key in the list was obtained.


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = {1, 2, 3, 4, 5};
<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001]2^SB001]1^JB001]2"_var);
dim d2 = {"A", "B", "C"};</code></pre>
if (readnext(ID, MV)) ... ok // ID -> "SB001" // MV -> 2</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>dim d1 = v1;</td><td>Initialise all elements of an array to some single value or constant. A var, "", 0 etc.
<tr><td>if</td><td>readnext(out record, out key, out valueno)</td><td><p>Get the next record, key and value no from an active select list.
</p>
<p><em>record:</em> [out] Is only available in select lists that have been created with the final (R) option. Otherwise the record will be returned as an empty string and must be obtained using a db read() function.
</p>
<p><em>key:</em> [out] A string. Typically the key of a db file record.
</p>
<p><em>valueno:</em> [out] Is only available in select lists that have been created by sort/select commands that refer to multi-valued db dictionary fields where db records have multiple values for a specific field.
</p>
<em>Returns:</em> True if an active select list was available and the next key in the list was obtained.


<pre><code class='hljs-ncdecl language-javascript'>dim d1(10);
<pre><code class='hljs-ncdecl language-javascript'>select("xo_clients by name (R)");
d1 = "";</code></pre>
if (readnext(RECORD, ID, MV)) ... ok;
assert(not RECORD.empty());</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>d1.redim(nrows, ncols = 1)</td><td>Resize an array to a different number of rows and columns.</p>
<tr><td></td><td>pushselect(out cursor)</td><td><p>Saves a pointer to the currently active select list.
Existing data will be retained as far as possible. Any additional elements are unassigned.</p>
</p>
Resizing rows to 0 clears all data.</p>
<p>This allows another select list to be activated and used temporarily before the original select list is reactivated.
Resizing cols to 0 clears all data and changes its status to "undimensioned".
</p>
<em>cursor:</em> [out] A var that can be passed later on to the popselect() function to reactivate the saved list.


<pre><code class='hljs-ncdecl language-javascript'>dim d1;
<pre><code class='hljs-ncdecl language-javascript'>select("xo_clients by name");
d1.redim(10, 3);</code></pre>
var saved_xo_clients_cursor;
pushselect(saved_xo_clients_cursor);
//
// ... work with another select list ...
//
popselect(saved_xo_clients_cursor); // Reactivate the original select list.</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>d1.swap(d2) </td><td>Swap one array with another.</p>
<tr><td></td><td>popselect(cursor)</td><td><p>Re-establish an active select list saved by pushselect().
Either or both may be undimensioned.
</p>
<p><em>cursor:</em> A var created by the pushselect() function.
</p>
See pushselect() for more info.</td></tr>
<tr><td></td><td>clearselect()</td><td><p>Deactivate an active select list.
</p>
If no select list is active then nothing is done.


<pre><code class='hljs-ncdecl language-javascript'>dim d1(5);
<pre><code class='hljs-ncdecl language-javascript'>clearselect();</code></pre>
dim d2(10);
d1.swap(d2);</code></pre>


</td></tr>
</td></tr>
</table>
<tr><td>if</td><td>deleterecord(filename)</td><td><p>Use an active select list to delete db records.
<h5 id=Array_Access>Array Access</h5>
</p>
<p><em>Returns:</em> False if any records could not be deleted.
</p>
Contrast this function with the two argument "deleterecord(file, key)" function that deletes a single record.


<table class=wikitable>
<pre><code class='hljs-ncdecl language-javascript'>if (select("xo_clients with type 'Q' and with balance between 0 and 100")) {
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
  if (deleterecord("xo_clients")) ...
<tr><td></td><td>var v1 = d1[rowno];</br>d1[rowno] = v1;</td><td>Access and update elements of a one dimensional array using [] brackets
}</code></pre>
 
<pre><code class='hljs-ncdecl language-javascript'>dim d1 = {1, 2, 3, 4, 5};
d1[3] = "X";
let v1 = d1[3]; // "X"</code></pre>


</td></tr>
</td></tr>
<tr><td></td><td>var v1 = d1[rowno, colno];</br>d1[rowno, colno] = v1;</td><td>Access and update elements of an two dimensional array using [] brackets
<tr><td>if</td><td>deleterecord(dbfile, key)</td><td>Delete a single database file record.


<pre><code class='hljs-ncdecl language-javascript'>dim d1(10, 5);
<pre><code class='hljs-ncdecl language-javascript'>let file = "xo_clients", key = "QQ001";
d1 = "";
write("" on file, key);
d1[3, 4] = "X";
if (not deleterecord(file, key)) ...
let v1 = d1[3, 4]; // "X"</code></pre>
// or
write("" on file, key);
if (not file.deleterecord(key)) ...</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>d1.rows()</td><td>Get the number of rows in the dimensioned array</p>
<tr><td>if</td><td>savelist(listname)</td><td><p>Save a currently active select list under a given name.
<em>Returns:</em> A count. Can be zero, indicating an empty array.
</p>
<p>After saving, the list is no longer active and hasnext() will return false.
</p>
<p><em>Returns:</em> True if an active select list was saved, false if there was no active select list.
</p>
Lists are saved as a record in the "lists" file.


<pre><code class='hljs-ncdecl language-javascript'>dim d1(5,3);
<pre><code class='hljs-ncdecl language-javascript'>selectkeys("SB001^SB002"_var);
let v1 = d1.rows(); // 5</code></pre>
if (not savelist("my_list")) ...</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>d1.cols()</td><td>Get the number of columns in the dimensioned array</p>
<tr><td>if</td><td>getlist(listname)</td><td><p>Reactivate a saved select list of a given name.
<em>Returns:</em> A count.  0 if the array is undimensioned.
</p>
<p>A saved list is obtained from the "lists" file and activated.
</p>
<em>Returns:</em> True if an active select list was successfully reactivated, otherwise false.


<pre><code class='hljs-ncdecl language-javascript'>dim d1(5,3);
<pre><code class='hljs-ncdecl language-javascript'>if (not getlist("my_list")) ...</code></pre>
let v1 = d1.cols(); // 3</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>d1.join(delimiter = FM)</td><td>Joins all elements into a single delimited string</p>
<tr><td>if</td><td>deletelist(listname)</td><td><p>Remove a saved select list by name.
<em>delimiter:</em> Default is FM.</p>
</p>
<em>Returns:</em> A string var.
A saved list is deleted from the "lists" file.


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = {"f1", "f2", "f3"};
<pre><code class='hljs-ncdecl language-javascript'>if (not deletelist("my_list")) ...</code></pre>
let v1 = d1.join(); // "f1^f2^f3"_var</code></pre>


</td></tr>
</td></tr>
</table>
</table>
<h5 id=Array_Mutation>Array Mutation</h5>
<h5 id=Perform/Execute>Perform/Execute</h5>


<table class=wikitable>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td></td><td>d1.splitter(str1, delimiter = FM)</td><td>Creates or updates the array from a given string.</p>
<tr><td>var=</td><td>perform(command_line)</td><td><p>Run an exodus program/library's main function using a command like syntax similar to that of executable programs.
If the dim array is undimensioned it will be dimensioned with the number of elements that the string has fields.</p>
</p>
If the dim array is dimensioned and has more elements than there are fields in the string, the excess array elements are initialised to "". If the record has more fields than there are elements in the array, the excess fields are all left unsplit in the final element of the array.</p>
<p>A "command line" is passed to the program/library in the usual COMMAND, SENTENCE and OPTIONS environment variables instead of function arguments.
Predimensioning arrays allows the efficient reuse of arrays in loops and ensures that all elements are assigned values, useful when reading records from db files.</p>
</p>
Using undimensioned arrays allows the efficient handling of arrays with a very variable number of elements. e.g. os text files.
<p>The program/library's main function should have zero arguments. Performing a program/library function with main arguments results in them being unassigned and in some case core dump may occur.
</p>
<p>The following environment variables are initialised on entry to the main function of the program/library. They are preserved untouched in the calling program.
</p>
<p>SENTENCE, COMMAND, OPTIONS: Initialised from the argument "command_line".
</p>
<p>RECUR0, RECUR1, RECUR2, RECUR3, RECUR4 to "".
</p>
<p>ID, RECORD, MV, DICT initialised to "".
</p>
<p>LEVEL is incremented by one.
</p>
<p>All other environment variables are shared between the caller and callee. There is essentially only one environment in any one process or thread.
</p>
<p>Any active select list is passed to the performed program/library and can be consumed by it. Conversely any active select list created by the performed program/library will be returned to the calling program. In other words, both the performing and the performed programs/libraries share a single active select list environment. This is different from execute() which gets its own private active select list, initially inactive.
</p>
<p><em>command_line:</em> The first word of this argument is used as the name of the program/library to be loaded and run. command_line is used to initialise the SENTENCE, COMMAND and OPTIONS environment variables.
</p>
<p><em>Returns:</em> Whatever var the program/library returns, or "" if it calls stop() or abort(()".
</p>
<p>The return value can be ignored and discarded without any compiler warning.
</p>
Exodus program/libraries may also be called directly using conventional function calling syntax. To call an exodus program/library called progname using either the syntax "call progname(args...);" or "var v1 = progname(args...);" you must "#include <progname.h>" after the "programinit()" or "libraryinit()" lines in your program/library.</td></tr>
<tr><td>var=</td><td>execute(command_line)</td><td><p>Run an exodus program/library's main function.
</p>
Identical to perform() but any currently active select list in the calling program/library is not accessible to the executed program/library and is preserved in the calling [program as is. Any select list created by the executed library is discarded when it terminates.</td></tr>
<tr><td></td><td>chain(command_line)</td><td><p>Run an exodus program/library's main function after closing the current program.
</p>
Identical to perform() except that the current program closes first.</td></tr>
<tr><td>var=</td><td>libinfo(libname)</td><td>Check if a lib exists to be performed/executed or called.</td></tr>
</table>
<h5 id=Program_Termination_>Program Termination </h5>


<pre><code class='hljs-ncdecl language-javascript'>dim d1;
<table class=wikitable>
d1.splitter("f1^f2^f3"_var); // d1.rows() -> // Automatically dimensioned.
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
//
<tr><td></td><td>stop(message = "")</td><td><p>Stop the current exodus program/library normally and return to the parent exodus program/library, or return to the operating system if none.
dim d2(10);
</p>
d2.splitter("f1^f2^f3"_var); // d2.rows() -> 10 // Predimensioned. Excess elements become ""</code></pre>
<p>Calling stop() in an exodus OS command line executable program, or in a function called from the same, will terminate the OS process with an error status of 0 which is generally considered to indicate success.
</p>
Calling stop() in a performed or executed exodus program/library, or in a function called from the same, will terminate the program/library being executed and return to the exodus program that performed or executed it.</td></tr>
<tr><td></td><td>abort(message = "")</td><td><p>Abort the current exodus program/library abnormally and return to the parent exodus program/library, or return to the operating system if none.
</p>
Similar to stop() but, if terminating the OS process, then return an error status of 1 which is generally considered to be an indication of failure.</td></tr>
<tr><td></td><td>abortall(message = "")</td><td><p>Abort the current exodus program/library abnormally and return to the parent exodus program/library, or return to the operating system if none.
</p>
Similar to abort() but, if terminating the OS process, then return an error status of 2 which is generally considered to be an indication of failure.</td></tr>
<tr><td></td><td>logoff(message = "")</td><td></td></tr>
</table>
<h5 id=DB_File_Dictionaries>DB File Dictionaries</h5>


</td></tr>
<table class=wikitable>
<tr><td></td><td>d1.sorter(reverse = false)</td><td>Sort the elements of the array in place.</p>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<em>reverse:</em> Defaults to false. If true, then the order is reversed.
<tr><td>var=</td><td>calculate(dictid)</td><td><p>given dictid reads dictrec from DICT file and extracts from RECORD/ID or calls library
</p>
called dict+DICT function dictid not const so we can mess with the library?</td></tr>
<tr><td>var=</td><td>calculate(dictid, dictfile, id, record, mv = 0)</td><td></td></tr>
<tr><td>var=</td><td>xlate(filename, key, fieldno_or_name, mode)</td><td></td></tr>
</table>
<h5 id=I/O_Conversion>I/O Conversion</h5>


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "2,20,10,1"_var.split(",");
<table class=wikitable>
d1.sorter();
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
let v1 = d1.join(","); // "1,2,10,20"_var</code></pre>
<tr><td>var=</td><td>oconv(input, conversion)</td><td><p>iconv/oconv with access to exoprogram's environment variables.
</p>
<p>exoprog's iconv/oconv have the ability to call custom functions like "[funname,args...]"
</p>


<p>[NUMBER]  // built-in. See doc below.
</p>
<p>[DATE]    // built-in. See doc below.
</p>
<p>[DATEPERIOD]  e.g. [DATEPERIOD,1] [DATEPERIOD,1,12]
</p>
<p>[DATETIME]    e.g. [DATETIME,4*,DOS] [DATETIME,4*,MTS] [DATETIME,4*]
</p>
<p>[TIME2]      e.g. [TIME2,MT] [TIME2,MTS] [TIME2,MTS48]
</p>
</td></tr>
</td></tr>
<tr><td></td><td>d1.reverser()</td><td>Reverse the elements of the array in place.
<tr><td>var=</td><td>iconv(input, conversion)</td><td></td></tr>
</table>
<h5 id=Ioconv_Date/Time_>Ioconv Date/Time </h5>


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "2,20,10,1"_var.split(",");
<table class=wikitable>
d1.reverser();
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
let v1 = d1.join(","); // "1,10,20,2"_var</code></pre>
<tr><td>var=</td><td>iconv|oconv(var, "[DATE]")</td><td><p>Use iconv/oconv code "[DATE,args]" when you want date conversion to depend on the environment variable DATEFMT, particularly its American/International setting. Otherwise use ordinary "D" conversion codes directly for slightly greater performance.
</p>


</td></tr>
<p><em>var:</em> [oconv] An internal date (a number).
<tr><td></td><td>d1.shuffler()</td><td>Randomly shuffle the order of the elements of the array in place.
</p>
<p><em>Returns:</em> [oconv] A readable date in text format depending on "[DATE,args]" e.g. "31 DEC 2020" "31/12/2020" "12/31/2020"
</p>
<p><em>var:</em> [iconv] A date in text format as above.
</p>
<p><em>Returns:</em> [iconv] An internal date (a number) or "" if the input could not be understood as a valid date.
</p>
<p><em>args:</em> If args is empty then DATEFMT is used as the conversion code. If args starts with "D" then args is used as the conversion codes but any E option in DATEFMT is appended. If args does not start with "D" then args are appended to DATEFMT, a "Z" option is appended, and the result used as the conversion code. A "*" option is equivalent to a second "Z" option.
</p>
If you are calling iconv/oconv in code and DATEFMT is adequate for your needs then pass it directly as a function argument e.g. 'var v1 = iconv|oconv(v2, DATEFORMAT);' instead of indirectly like 'var v1 = iconv|oconv(v2, "[DATE]");'.


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "2,20,10,1"_var.split(",");
<pre><code class='hljs-ncdecl language-javascript'>let v1 = iconv("JAN 9 2020", "D");
d1.shuffler();
assert(oconv(v1, "[DATE]"  ) == " 9/ 1/2020");  // "D/EZ" or "[DATE,D]" equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
let v1 = d1.join(","); // random</code></pre>
assert(oconv(v1, "[DATE,4]" ) == " 9/ 1/2020"); // "D4Z"  equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
assert(oconv(v1, "[DATE,*4]") == "9/1/2020");   // "D4ZZ" equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)
assert(oconv(v1, "[DATE,*]" ) == "9/1/20");     // "DZZ"  equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)</code></pre>


</td></tr>
</td></tr>
</table>
<tr><td>var=</td><td>iconv|oconv(var, "[NUMBER]")</td><td><p>Use iconv/oconv "[NUMBER,args]" either when your numbers have currency or unit code suffixes or when you want number conversion to depend on the environment variable BASEFMT to determine thousands separator and decimal point. Otherwise use ordinary "MD" conversion codes directly for slightly greater performance.
<h5 id=Array_Conversion>Array Conversion</h5>
</p>
<p>Formatting for numbers with optional currency code/unit suffix and is sensitive to the International or European setting in BASEFMT regarding use of commas or dots for thousands separators and decimal points.
</p>
<p>Primarily used for oconv() but can be used in reverse for iconv.
</p>
<p><em>var:</em> A number with an optional currency code or unit suffix. e.g. "12345.67USD"
</p>
<p><em>Returns:</em> A formatted number with thousands separated conventionally e.g. "12.345.67USD".
</p>
<p>iconv/oconv("[NUMBER]")      oconv leaves ndecimals untouched as in the input. iconv see below.
</p>
<p>iconv/oconv("[NUMBER,2]")    Specified number of decimal places
</p>
<p>iconv/oconv("[NUMBER,BASE]") Decimal places as per BASEFMT
</p>
<p>iconv/oconv("[NUMBER,*]")    Leave decimal places untouched as in the input
</p>
<p>iconv/oconv("[NUMBER,X]")    Leave decimal places untouched as in the input
</p>
<p>iconv/oconv("[NUMBER,2Z]")  Z (suppress zero) combined with any other code for oconv results in empty output "" instead of "0.00" in case of zero input.
</p>
 
<p>Empty input "" gives empty output "".
</p>


<table class=wikitable>
<p>All leading, trailing and internal spaces are removed from the input.
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
</p>
<tr><td>dim=</td><td>d1.sort(reverse = false)</td><td>Same as sorter() but returns a new array leaving the original untouched.</td></tr>
 
<tr><td>dim=</td><td>d1.reverse()</td><td>Same as reverser() but returns a new array leaving the original untouched.</td></tr>
<p>A trailing currency or unit code is ignored and returned on output.
<tr><td>dim=</td><td>d1.shuffle()</td><td>Same as shuffler() but returns a new array leaving the original untouched.</td></tr>
</p>
</table>
<h5 id=Array_DB_I/O>Array DB I/O</h5>


<table class=wikitable>
<p>An exodus number is an optional leading + or - followed by one or more decimal digits 0-9 with a single optional decimal point placed anywhere.
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
</p>
<tr><td></td><td>d1.write(dbfile, key)</td><td>Writes a db file record created from an array.</p>
Each element in the array becomes a separate field in the db record. Any redundant trailing FMs are suppressed.


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "Client GD^G^20855^30000^1001.00^20855.76539"_var.split();
<p>If the input is non-numeric then "" is returned and STATUS set to 2. In the case of oconv with multiple fields or values each field or value is processed separately but STATUS is set to 2 if any are non-numeric.
let file = "xo_clients", key = "GD001";
</p>
if (not deleterecord("xo_clients", "GD001")) {}; // Cleanup first
d1.write(file, key);
// or
write(d1 on file, key);</code></pre>


</td></tr>
<p>iconv removes and oconv adds thousand separator chars. The thousands separator is  "," if BASEFMT starts with "MD" or "." if it starts with "MC".
<tr><td>if</td><td>d1.read(dbfile, key)</td><td>Read a db file record into an array.</p>
</p>
Each field in the database record becomes a single element in the array.</p>
<em>Returns:</em> True if the record exists or false if not,</p>
If the array is predimensioned then any excess array elements are initialised to "" and any excess record fields are left unsplit in the final array element. See dim splitter for more info.</p>
If the array is not predimensioned (rows and cols = 0) then it will be dimensioned to have exactly the same number of rows as there are fields in the record being read.


<pre><code class='hljs-ncdecl language-javascript'>dim d1(10);
<p><em>oconv:</em>
let file = "xo_clients", key = "GD001";
</p>
if (not d1.read(file, key)) ... // d1.join() -> "Client GD^G^20855^30000^1001.00^20855.76539^^^^"_var
// or
if (not read(d1 from file, key)) ...</code></pre>


</td></tr>
<p>Add thousands separator chars and optionally standardise the number of decimal places.
</table>
</p>
<h5 id=Array_OS_I/O>Array OS I/O</h5>


<table class=wikitable>
<p>Multiple numbers in fields, values, subvalues etc. can be processed in one string.
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
</p>
<tr><td>if</td><td>d1.oswrite(osfilename, codepage = "")</td><td>Creates an entire os text file from an array</p>
Each element of the array becomes one line in the os file delimited by \n</p>
Any existing os file is overwritten and replaced.</p>
<em>codepage:</em> Optional: Data is converted from UTF8 to the required codepage/encoding before output. If the conversion cannot be performed then return false.</p>
<em>Returns:</em> True if successful or false if not.


<pre><code class='hljs-ncdecl language-javascript'>dim d1 = "aaa=1\nbbb=2\nccc=3\n"_var.split("\n");
<p>Any leading + character is preserved on output.
if (not osremove("xo_conf.txt")) {}; // Cleanup first
</p>
let osfilename = "xo_conf.txt";
 
if (not d1.oswrite(osfilename)) ...
<p>Z suppresses zeros and returns empty string "" instead.
// or
</p>
if (not oswrite(d1 on osfilename)) ...</code></pre>
 
<p>Special format "[NUMBER,ndecs,move_ndecs]": move_ndecs causes decimal point to be shifted left if positive or right if negative.
 
<pre><code class='hljs-ncdecl language-javascript'>var v1 = oconv("1234.5USD", "[NUMBER,2]"); // "1,234.50USD" // Comma added and decimal places corrected.</code></pre>
 
 
</p>
<p><em>iconv:</em>
</p>
 
<p>Remove all thousands separator chars and optionally standardise the number of decimal places.
</p>
 
<p>If ndecs is not specified in the "[NUMBER]" pattern then ndecs is taken from the current RECORD using dictionary code NDECS if DICT is available otherwise it uses ndecs from BASEFMT.
</p>
 
<p>iconv only handles a single field/value.
</p>


</td></tr>
Optional prefix of "1/" or "/" causes the reciprocal of the number to be used. e.g. "1/100" or "/100" -> "0.01".
<tr><td>if</td><td>d1.osread(osfilename, codepage = "")</td><td>Read an entire os text file into an array.</p>
Each line in the os file, delimited by \n or \r\n, becomes a separate element in the array.</p>
Existing data in the array is lost and the array is redimensioned to the number of lines in the input data.</p>
<em>codepage:</em> Optional. Data will be converted from the specified codepage/encoding to UTF8 after being read. If the conversion cannot be performed then return false.</p>
<em>Returns:</em> True if successful or false if not.</p>
If the first \n in the file is \r\n then the whole file will be split using \r\n as delimiter.


<pre><code class='hljs-ncdecl language-javascript'>dim d1;
<pre><code class='hljs-ncdecl language-javascript'>var v1 = iconv("1,234.5678USD", "[NUMBER]"); // "1234.57USD" // Comma removed</code></pre>
let osfilename = "xo_conf.txt";
if (not d1.osread(osfilename)) ... // d1.join("\n") -> "aaa=1\nbbb=2\nccc=3\n"_var0
// or
if (not osread(d1 from osfilename)) ...</code></pre>


</td></tr>
</td></tr>
<tr><td>var=</td><td>amountunit(input0, out unitx)</td><td><p>Split amount+currency code/unit string into number and currency code/unit.
</p>
<p><em>var:</em> "123.45USD"
</p>
<p><em>Returns:</em> e.g. "123.45"
</p>
<em>unitx:</em> [out] e.g. "USD"</td></tr>
<tr><td>var=</td><td>amountunit(input0)</td><td></td></tr>
</table>
<h5 id=Time/Date_Utilities>Time/Date Utilities</h5>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>timedate2()</td><td>
<p><em>Returns:</em> Text of date and time in users time zone
</p>
<p>e.g. "2MAR2025 11:52AM"
</p>
Offset from UTC by TZ seconds.</td></tr>
<tr><td></td><td>getdatetime(out user_date, out user_time, out system_date, out system_time, out UTC_date, out UTC_time)</td><td>
<p><em>Returns:</em> User, server and UTC date and time
</p>
<p>User date and time is determined by adding the environment variable TZ.f(1)'s TZ offset (in seconds) to UTC date/time obtained from the operating system.
</p>
<p>"system" date and time is normally the same as UTC date/time and is determined by adding the environment variable TZ.f(2)'s TZ offset (in seconds) to UTC date/time obtained from the operating system.
</p>
</td></tr>
<tr><td>var=</td><td>elapsedtimetext()</td><td><p>Get text of elapsed time since environment variable TIMESTAMP was initialised with ostimestamp() at program/thread startup.
</p>
TIMESTAMP can be updated using ostimestamp() as and when desired.
<pre><code class='hljs-ncdecl language-javascript'>var v1 = elapsedtimetext(); // e.g. "< 1ms"</code></pre>
</td></tr>
<tr><td>var=</td><td>elapsedtimetext(timestamp1, timestamp2)</td><td>Get text of elapsed time between two timestamps
<pre><code class='hljs-ncdecl language-javascript'>let v1 = elapsedtimetext(0, 0.55);  // "13 hours, 12 mins"
let v2 = elapsedtimetext(0, 0.001); // "1 min, 26 secs"</code></pre>
</td></tr>
</table>
<h5 id=Terminal_I/O_Utilities>Terminal I/O Utilities</h5>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td></td><td>note(msg, options, io response)</td><td><p>If stdin is a terminal, output a message to stdout and optionally pause processing and request a response from the user, otherwise set the response to "" and continue.
</p>
<em>options:</em> R = Response requested. C upper case response.
<pre><code class='hljs-ncdecl language-javascript'>var response;
// call note("Enter something", "RC", response);</code></pre>
</td></tr>
<tr><td></td><td>note(msg)</td><td>Output a message to stdin and continue.
<pre><code class='hljs-ncdecl language-javascript'>call note("Hello world.");</code></pre>
</td></tr>
<tr><td>var=</td><td>decide(question, options = "")</td><td><p>If stdin is a terminal, pause processing, list some given options to stdout and request the user to make a choice, otherwise set the response to "" and continue.
</p>
<em>Returns:</em> The chosen option (value not number) or "" if the user cancelled.</td></tr>
<tr><td>var=</td><td>decide(question, options, out reply, defaultreply = 1)</td><td><p>Same as decide() above but extended.
</p>
<p><em>defaultreply:</em> A default option if the user presses Enter.
</p>
<em>reply:</em> [out] The option number that the user chose or "" if they cancelled.</td></tr>
<tr><td>if</td><td>esctoexit()</td><td><p>If stdin is a terminal, check if a key has been pressed and, if so, pause execution and ask the user to confirm if they want to escape/cancel or resume processing.
</p>
<em>Returns:</em> True if a key has been pressed and the user confirms to escape/cancel. False if no key has been pressed or the user chooses to resume and not escape/cancel.</td></tr>
<tr><td>var=</td><td>AT(code)</td><td><p>Get a string to control terminal operation.
</p>
<p><em>Returns:</em> A string to be output to the terminal in order to accomplish the desired operation.
</p>
<p>The terminal protocol is xterminal.
</p>
<p><em>code:</em>
</p>
<p>n  Position the cursor at column number n
</p>
<p>0  Position the cursor at column number 0
</p>
<p>-1  Clear the screen and home the cursor
</p>
<p>-2  Position the cursor at the top left home (x,y = 0,0)
</p>
<p>-3  Clear from the cursor at the end of screen
</p>
<p>-4  Clear from cursor to end of line
</p>
-40 Position the cursor at columnno 0 and clear to end of line</td></tr>
<tr><td>var=</td><td>AT(x, y)</td><td><p>Get a terminal cursor positioning string.
</p>
<p><em>Returns:</em> A string to be output to the terminal to position the cursor at the desired screen x and y position.
</p>
The terminal protocol is xterminal.</td></tr>
<tr><td>if</td><td>getcursor(out cursor, delayms = 3000, max_errors = 0)</td><td><p>Get the position of the terminal cursor.
</p>
<p><em>cursor:</em> [out] If stdin is a terminal, an FM delimited string containing the x and y coordinates of the current terminal cursor.
</p>
<p>If stdin is not a terminatl then an empty string "" is returned.
</p>
<p>The cursor additionally contains a third field which contains the delay in ms from the terminal.
</p>
<p>The FM delimited string returned can be later passed to setcursor() to reposition the cursor back to its original position or it can be parsed and used accordingly.
</p>
<p><em>delayms:</em> Default 3000ms. The maximum time to wait for terminal response.
</p>
<p><em>max_errors:</em> Default is 0. If not zero, reset the number of times to error before automatically disabling getcursor(). max_errors is initialised to 3. If negative then max_errors has the the effect of disabling all future calls to getcursor().
</p>
<p>In case the terminal fails to respond correctly within the required timeout, or is currently disabled due to too many failures, or has been specifically disabled then the returned "cursor" var contains a 4th field:
</p>
<p>TIMEOUT - The terminal failed to respond within the timeout.
</p>
<p>READ_ERROR - Failed to read terminal response.
</p>
<p>INVALID_RESPONSE - Terminal response invalid.
</p>
<p>SETUP_ERROR - Terminal setup failed.
</p>
DISABLED - Terminal is disabled due to more errors than the maximum currently set.
<pre><code class='hljs-ncdecl language-javascript'>var cursor;
if (isterminal() and not getcursor(cursor)) ... // cursor becomes something like "0^20^0.012345"_var</code></pre>
</td></tr>
<tr><td>var=</td><td>getcursor()</td><td><p>Get the position of the terminal cursor.
</p>
For more info see the main getcursor() function above.
<pre><code class='hljs-ncdecl language-javascript'>let cursor = getcursor(); // If isterminal() then cursor becomes something like "0^20^0.012345"_var</code></pre>
</td></tr>
<tr><td></td><td>setcursor(cursor_coordinates)</td><td><p>If stdin is a terminal, position the cursor at x and y as per the given coordinates.
</p>
<em>cursor_coordinates:</em> An FM delimited string containing the x and y coordinates of the terminal cursor as can be obtained by getcursor().
<pre><code class='hljs-ncdecl language-javascript'>if (isterminal()) {
    let cursor = getcursor(); // Save the current cursor position.
    TRACE(cursor)            // Show the saved cursor position.
    print(AT(0,0));          // Position the cursor at 0,0.
    setcursor(cursor);        // Restore its position
}</code></pre>
</td></tr>
</table>
<h5 id=Array_Utilities>Array Utilities</h5>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>var=</td><td>invertarray(input, pad = false)</td><td><p>Dynamic array fields become values and vice versa
</p>
<p><em>Returns:</em> The inverted dynamic array.
</p>
<em>pad:</em> If true then on return, all fields will have the same number of values with superfluous trailing VMs where necessary.
<pre><code class='hljs-ncdecl language-javascript'>let v1 = "a]b]c^1]2]3"_var;
let v2 = invertarray(v1); // "a]1^b]2^c]3"_var</code></pre>
</td></tr>
<tr><td></td><td>sortarray(io array, fns = "", order = "")</td><td><p>Sorts fields of multivalues of dynamic arrays in parallel
</p>
<p><em>fns:</em> VM separated list of field numbers to sort in parallel based on the first field number
</p>
<p><em>order:</em>
</p>
<p>AL Ascending  - Left Justified  - Alphabetic
</p>
<p>DL Descending - Left Justfiied  - Alphabetic
</p>
<p>AR Ascending  - Right Justified - Numeric
</p>
DR Descending - Right Justified - Numeric
<pre><code class='hljs-ncdecl language-javascript'>var v1 = "f1^10]20]2]1^ww]xx]yy]zz^f3^f4"_var;  // fields 2 and 3 are parallel multivalues and currently unordered.
sortarray(v1, "2]3"_var, "AR"); // v1 -> "f1^1]2]10]20^zz]yy]ww]xx^f3^f4"_var</code></pre>
</td></tr>
</table>
<h5 id=Record_Locking>Record Locking</h5>
<table class=wikitable>
<tr> <th>Use</th> <th>Function</th> <th>Description</th> </tr>
<tr><td>if</td><td>lockrecord(filename, io file, keyx, recordx, waitsecs = 0, allowduplicate = false)</td><td>Does not actually return record</td></tr>
<tr><td>if</td><td>lockrecord(filename, io file, keyx)</td><td></td></tr>
<tr><td>if</td><td>unlockrecord(filename, io file, key)</td><td></td></tr>
<tr><td>if</td><td>unlockrecord()</td><td></td></tr>
</table>
</table>



Revision as of 20:16, 25 March 2025


Var

Use Function Description
Var Creation
Use Function Description
var v1;

Create an unassigned var.

Unassigned variables can be assigned conditionally in if/else statements or used as outbound arguments of function calls.

A runtime error is thrown if a var is used before being assigned so silent "use before assign" bugs cannot occur.
var client; // Unassigned var
if (not read(client from "xo_clients", "SB001")) ...
var v1 = expression;

Assign a var using a literal or an expression.

Use "let" instead of "var" wherever possible as a shorthand way of writing "const var".
var v1 = 42;                 // Integer
var v2 = 42.3;               // Double
var v3 = "abc";              // String
var v4 = 'x';                // char
var v5 = true;               // bool

var v6 = v1 + 100;           // Arithmetic
var v7 = v3 ^ "xyz";         // Concatenation
var v8 = oslist(".").sort(); // Built in functions

let v9 = 12345;              // A const var

var v10 = 12'345_var;        // A literal var integer
var v11 = 123.45_var;        // A literal var double
var v12 = "f1^v1]v2^f3"_var; // A literal var string

var x = 0.1, y = "0.2", z = x + y; // z -> 0.3
ifv1.assigned() Returns: True if the var is assigned, otherwise false
ifv1.unassigned() Returns: True if the var is unassigned, otherwise false
var=v2.or_default(defaultvalue)

Returns: A copy of the var if it is assigned or the default value if it is not.

Can be used to handle optional arguments in functions.

defaultvalue: Cannot be unassigned.

var v1; // Unassigned
var v2 = v1.or_default("abc"); // v2 -> "abc"
// or
var v3 = or_default(v1, "abc");

Mutator: defaulter()

v1.defaulter(defaultvalue)

If the var is unassigned then assign the default value to it, otherwise do nothing.

defaultvalue: Cannot be unassigned.
var v1; // Unassigned
v1.defaulter("abc"); // v1 -> "abc"
// or
defaulter(v1, "abc");
v1.swap(io v2)

Swap the contents of one var with another.

Useful for stashing large strings quickly. They are moved using pointers without making copies or allocating memory.

Eiher or both variables may be unassigned.
var v1 = space(65'536);
var v2 = "";
v1.swap(v2); // v1 -> "" // v2.len() -> 65'536
// or
swap(v1, v2);
var=v2.move()

Force the contents of a var to be moved instead of copied. The moved var becomes an empty string.

This allows large strings to be handled efficiently. They are moved using pointers without making copies or allocating memory.

The moved var must be assigned otherwise a VarUnassigned error is thrown.
var v1 = space(65'536);
var v2 = v1.move(); // v2.len() -> 65'536 // v1 -> ""
// or
var v3 = move(v2);
var=v2.clone()

Returns a copy of the var.

The cloned var may be unassigned, in which case the copy will be unassigned too.
var v1 = "abc";
var v2 = v1.clone(); // "abc"
// or
var v3 = clone(v2);
var=v1.dump()

Return a string describing internal data of a var.

If the str is located on the heap then its address is given.

typ:

0x01 str is available.

0x02 int is available.

0x04 dbl is available.

0x08 nan: str is not a number.

0x16 osfile: str, int and dbl have special meaning.
var v1 = str("x", 32);
v1.dump().outputl(); /// e.g. var:0x7ffea7462cd0 typ:1 str:0x584d9e9f6e70 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
// or
outputl(dump(v1));
Arithmetical Operators
Use Function Description
ifv1.isnum()

Checks if a var is numeric.

Returns: True if a var holds a double, an integer, or a string that is defined as numeric.

A string is defined as numeric only if it consists of one or more digits 0-9, with an optional decimal point "." placed anywhere, with an optional + or - sign prefix, or it is the empty string "", which is defined to be zero.
if ("+123.45"_var.isnum()) ... ok
if (       ""_var.isnum()) ... ok
if (not   "."_var.isnum()) ... ok
// or
if (isnum("123.")) ... ok
var=v1.num()

Returns a copy of the var if it is numeric or 0 otherwise.

Returns: A guaranteed numeric var

Allows working numerically with data that may be non-numeric.
var v1 = "123.45"_var.num();    // 123.45
var v2 = "abc"_var.num() + 100; // 100
var=v2 + v3

Addition

Attempts to perform numeric operations on non-numeric strings will throw a runtime error VarNonNumeric.

Floating point numbers are implicitly converted to strings with no more than 12 significant digits of precision. This practically eliminates all floatng point rounding errors.

Internally, 0.1 + 0.2 looks like this using doubles.

0.10000000000000003 + 0.20000000000000004 -> 0.30000000000000004
var v1 = 0.1;
var v2 = v1 + 0.2; // 0.3
var=v2 - v3Subtraction
var=v2 * v3Multiplication
var=v2 / v3Division
var=v2 % v3Modulus
v1 += v2Self addition
var v1 = 0.1;
v1 += 0.2; // 0.3
v1 -= v2Self subtraction
v1 *= v2Self multiplication
v1 /= v2Self division
v1 %= v2Self modulus
v1 ++Post increment
var v1 = 3;
var v2 = v1 ++; // v2 -> 3 // v1 -> 4
v1 --Post decrement
var v1 = 3;
var v2 = v1 --; // v2 -> 3 // v1 -> 2
++ v1Pre increment
var v1 = 3;
var v2 = ++ v1; // v2 -> 4 // v1 -> 4
-- v1Pre decrement
var v1 = 3;
var v2 = -- v1; // v2 -> 2 // v1 -> 2
Dynamic Array Creation, Access And Update
Use Function Description
var=""_var

The literal suffix "_var" allows dynamic arrays to be seamlessly embedded in code using a predefined set of visible equivalents of unprintable field mark characters as follows:

` = RM, Record mark

^ = FM, Field mark

] = VM, Value mark

} = SM, Subvalue mark

| = TM, Text mark

~ = ST, Subtext mark
var v1 = "f1^f2^v1]v2^f4"_var; // "f1" _FM "f2" _FM "v1" _VM "v2" _FM "f4"
var v1 = {"a", "b", "c" ...}; // Initializer listCreate a dynamic array var from a list. C++ constrains list elements to be all the same type: var, string, double, int, etc. but they all end up as fields of a dynamic array string.
var v1 = {11, 22, 33}; // "11^22^33"_var
var=v2(fieldno); v1(fieldno) = v2

Dynamic array - field extraction, update and append:

See also inserter() and remover().

var v1 = "aa^bb"_var;
v1(4) = 44; // v1 -> "aa^bb^^44"_var
// Field number -1 causes appending a field when updating.
v1(-1) = "55"; // v1 -> "aa^bb^^44^55"_var
Field access:

It is recommended to use "v1.f(fieldno)" syntax using a ".f(" prefix to access fields in expressions instead of plain "v1(fieldno)". The former syntax (using .f()) will always compile whereas the latter does not compile in all contexts. It will compile only if being called on a constant var or in a location which requires a var. This is due to C++ not making a clear distinction between usage on the left and right side of assignment operator =.

Furthermore using plain round brackets without the leading .f can be confused with function call syntax.
var v1 = "aa^bb^cc"_var;
var v2 = v1.f(2); // "bb" /// .f() style access. Recommended.
var v3 =   v1(2); // "bb" ///   () style access. Not recommended.
var=v2(fieldno, valueno); v1(fieldno, valueno) = v2

Dynamic array - value update and append

See also inserter() and remover().
var v1 = "aa^b1]b2^cc"_var;
v1(2, 4) = "44"; // v1 -> "aa^b1]b2]]44^cc"_var
// value number -1 causes appending a value when updating.
v1(2, -1) = 55; // v1 -> "aa^b1]b2]]44]55^cc"_var
Value access:
var v1 = "aa^b1]b2^cc"_var;
var v2 = v1.f(2,2); // "b2" /// .f() style access. Recommended.
var v3 =   v1(2,2); // "b2" ///   () style access. Not recommended.
String Creation
Use Function Description
var=v2 ^ v3

String concatention operator ^

At least one side must be a var.

"aa" ^ "22" will not compile but "aa" "22" will.

Floating point numbers are implicitly converted to strings with no more than 12 significant digits of precision. This practically eliminates all floatng point rounding errors.
var v2 = "aa";
var v1 = v2 ^ 22; // "aa22"
v1 ^= v2String self concatention ^= (append)
var v1 = "aa";
v1 ^= 22; // v1 -> "aa22"
var=varnum.round(ndecimals = 0)

Convert a number into a string after rounding it to a given number of decimal places.

Trailing zeros are not omitted. A leading "0." is shown where appropriate.

0.5 always rounds away from zero. i.e. 1.5 -> 2 and -2.5 -> -3

var: The number to be converted.

ndecimals: Determines how many decimal places are shown to the right of the decimal point or, if ndecimals is negative, how many 0's to the left of it.

Returns: A var containing an ASCII string of digits with a leading "-" if negative, and a decimal point "." if ndecimals is > 0.
let v1 = var(0.295).round(2);  //  "0.30"
// or
let v2 = round(1.295, 2);      //  "1.30"

var v3 = var(-0.295).round(2); // "-0.30"
// or
var v4 = round(-1.295, 2);     // "-1.30"

var v5 = round(0, 1);           // "0.0"
var v6 = round(0, 0);           // "0"
var v7 = round(0, -1);          // "0"
Negative number of decimals rounds to the left of the decimal point
let v1 = round(123456.789,  0); // "123457"
let v2 = round(123456.789, -1); // "123460"
let v3 = round(123456.789, -2); // "123500"
var=var::chr(num)

Get a char given an integer 0-255.

Returns: A string containing a single char

0-127 -> ASCII, 128-255 -> invalid UTF-8 which cannot be written to the database or used in many exodus string operations
let v1 = var::chr(0x61); // "a"
// or
let v2 = chr(0x61);
var=var::textchr(num)

Get a Unicode character given a Unicode Code Point (Number)

Returns: A single Unicode character in UTF8 encoding.
let v1 = var::textchr(171416); // "𩶘" // or "\xF0A9B698"
// or
let v2 = textchr(171416);
var=var::textchrname(unicode_code_point)

Get a Unicode character name

unicode_code_point: 0 - 0x10FFFF.

Returns: Text of the name or "" if not a valid Unicode Code Point
let v1 = var::textchrname(91); // "LEFT SQUARE BRACKET"
// or
let v2 = textchrname(91);
var=varstr.str(num)

Get a string of repeated substrings.

var: The substring to be repeated

num: How many times to repeat the substring

Returns: A string
let v1 = "ab"_var.str(3); // "ababab"
// or
let v2 = str("ab", 3);
var=var::space(nspaces)

Get a string containing a given number of spaces.

nspaces: The number of spaces required.

Returns: A string of space chars.
let v1 = var::space(3); // "␣␣␣"
// or
let v2 = space(3);
var=varnum.numberinwords(locale = "")

Returns: A string representing a given number written in words instead of digits.

locale: e.g. en_GB, ar_AE, el_CY, es_US, fr_FR etc or a language name e.g. "french".
let softhyphen = "\xc2\xad";
let v1 = var(123.45).numberinwords("de_DE").replace(softhyphen, " "); // "ein␣hundert␣drei␣und␣zwanzig␣Komma␣vier␣fünf"
String Scanning
Use Function Description
var=strvar.at(pos1)

Get a single char from a string.

pos1: First char is 1. Last char is -1.

Returns: A single char if pos1 ± the length of the string, or "" if greater. Returns the first char if pos1 is 0 or (-pos1) > length.
var v1 = "abc";
var v2 = v1.at(2);  // "b"
var v3 = v1.at(-3); // "a"
var v4 = v1.at(4);  // ""
var=strvar.ord()

Get the char number of a char

Returns: A number between 0 and 255.

If given a string, then only the first char is considered.

Equivalent to ord() in php
let v1 = "abc"_var.ord(); // 0x61 // decimal 97, 'a'
// or
let v2 = ord("abc");
var=strvar.textord()

Get the Unicode Code Point of a Unicode character.

var: A UTF-8 string. Only the first Unicode character is considered.

Returns: A number 0 to 0x10FFFF.

Equivalent to ord() in python and ruby, mb_ord() php.
let v1 = "Γ"_var.textord(); // 915 // U+0393: Greek Capital Letter Gamma (Unicode character)
// or
let v2 = textord("Γ");
var=strvar.len()

Get the length of a source string in number of chars

Returns: A number
let v1 = "abc"_var.len(); // 3
// or
let v2 = len("abc");
ifstrvar.empty()

Checks if the var is an empty string.

Returns: True if it is empty amd false if not.

This is a shorthand and more expressive way of writing 'if (var == "")' or 'if (var.len() == 0)' or 'if (not var.len())'

Note that 'if (var.empty())' is not exactly the same as 'if (not var)' because 'if (var("0.0")' is also defined as false. If a string can be converted to 0 then it is considered to be false. Contrast this with common scripting languages where 'if (var("0"))' is defined to be true.
let v1 = "0";
if (not v1.empty()) ... ok // true
// or
if (not empty(v1)) ... ok // true
var=strvar.textwidth()

Count the number of output columns required for a given source string.

Returns: A number

Allows wide multi-column Unicode characters that occupy more than one space in a text file or terminal screen.

Reduces combining characters to a single column. e.g. "e" followed by grave accent is multiple bytes but only occupies one output column.

Does not properly calculate all possible combining sequences of graphemes e.g. face followed by colour
let v1 = "🤡x🤡"_var.textwidth(); // 5
// or
let v2 = textwidth("🤡x🤡");
var=strvar.textlen()

Count the number of Unicode code points in a source string.

Returns: A number.
let v1 = "Γιάννης"_var.textlen(); // 7
// or
let v2 = textlen("Γιάννης");
var=strvar.fcount(sepstr)

Count the number of fields in a source string.

sepstr: The separator character or substr that delimits individual fields.

Returns: The count of the number of fields

This is similar to "var.count(sepstr) + 1" but it returns 0 for an empty source string.
let v1 = "aa**cc"_var.fcount("*"); // 3
// or
let v2 = fcount("aa**cc", "*");
var=strvar.count(sepstr)

Count the number of occurrences of a given substr in a source string.

substr: The substr to count.

Returns: The count of the number of sepstr found.

Overlapping substrings are not counted.
let v1 = "aa**cc"_var.count("*"); // 2
// or
let v2 = count("aa**cc", "*");
ifstrvar.starts(prefix)

Checks if a source string starts with a given prefix (substr).

prefix: The substr to check for.

Returns: True if the source string starts with the given prefix.

Returns: False if prefix is "". DIFFERS from c++, javascript, python3. See contains() for more info.
if ("abc"_var.starts("ab")) ... true
// or
if (starts("abc", "ab")) ... true
ifstrvar.ends(suffix)

Checks if a source string ends with a given suffix (substr).

suffix: The substr to check for.

Returns: True if the source string ends with given suffix.

Returns: False if suffix is "". DIFFERS from c++, javascript, python3. See contains() for more info.
if ("abc"_var.ends("bc")) ... true
// or
if (ends("abc", "bc")) ... true
ifstrvar.contains(substr)

Checks if a given substr exists in a source string.

substr: The substr to check for.

Returns: True if the source string starts with, ends with or contains the given substr.

Returns: False if suffix is "". DIFFERS from c++, javascript, python3

Human logic: "" is not equal to "x" therefore x does not contain "".

Human logic: Check each item (character) in the list for equality with what I am looking for and return success if any are equal.

Programmer logic: Compare as many characters as are in the search string for presence in the list of characters and return success if there are no failures.
if ("abcd"_var.contains("bc")) ... true
// or
if (contains("abcd", "bc")) ... true
var=strvar.index(substr, startchar1 = 1)

Find a substr in a source string.

substr: The substr to search for.

startchar1: The char position (1 based) to start the search at. The default is 1, the first char.

Returns: The char position (1 based) that the substr is found at or 0 if not present.
let v1 = "abcd"_var.index("bc"); // 2
// or
let v2 = index("abcd", "bc");
var=strvar.indexn(substr, occurrence)

Find the nth occurrence of a substr in a source string.

substr: The string to search for.

Returns: char position (1 based) or 0 if not present.
let v1 = "abcabc"_var.index("bc", 2); // 2
// or
let v2 = index("abcabc", "bc", 2);
var=strvar.indexr(substr, startchar1 = -1)

Find the position of substr working backwards from the end of the string towards the beginning.

substr: The string to search for.

Returns: The char position of the substr if found, or 0 if not.

startchar1: defaults to -1 meaning start searching from the last char. Positive start1char1 counts from the beginning of the source string and negative startchar1 counts backwards from the last char.
let v1 = "abcabc"_var.indexr("bc"); // 5
// or
let v2 = indexr("abcabc", "bc");
var=strvar.match(regex_str, regex_options = "")

Finds all matches of a given regular expression.

Returns: Zero or more matching substrings separated by FMs. Any groups are in VMs.

let v1 = "abc1abc2"_var.match("BC(\\d)", "i"); // "bc1]1^bc2]2"_var
// or
let v2 = match("abc1abc2", "BC(\\d)", "i");

regex_options:

l - Literal (any regex chars are treated as normal chars)

i - Case insensitive

p - ECMAScript/Perl (the default)

b - Basic POSIX (same as sed)

e - Extended POSIX

a - awk

g - grep

eg - egrep or grep -E

char ranges like a-z are locale sensitive if ECMAScript

m - Multiline. Default in boost (and therefore exodus)

s - Single line. Default in std::regex

f - First only. Only for replace() (not match() or search())

w - Wildcard glob style (e.g. *.cfg) not regex style. Only for match() and search(). Not replace().

var=strvar.match(regex)Ditto
var=strvar.search(regex_str, io startchar1, regex_options = "")

Search for the first match of a regular expression.

startchar1: [in] char position to start the search from

startchar1: [out] char position to start the next search from

Returns: The 1st match like match()

regex_options as for match()
var startchar1 = 1;
let v1 = "abc1abc2"_var.search("BC(\\d)", startchar1, "i"); // "bc1]1"_var // startchar1 -> 5 /// Ready for the next search
// or
startchar1 = 1;
let v2 = search("abc1abc2", "BC(\\d)", startchar1, "i");
var=strvar.search(regex_str)Ditto starting from first char
var=strvar.search(regex, io startchar1)Ditto given a rex
var=strvar.search(regex)Ditto starting from first char.
var=strvar.hash(std::uint64_t modulus = 0)

Get a hash of a source string.

modulus: The result is limited to [0, modulus)

Returns: A 64 bit signed integer.

MurmurHash3 is used.
let v1 = "abc"_var.hash(); assert(v1 == var(6'715'211'243'465'481'821));
// or
let v2 = hash("abc");
String Conversion - Non-Mutating - Chainable
Use Function Description
var=strvar.ucase()Convert to upper case
let v1 = "Γιάννης"_var.ucase(); // "ΓΙΆΝΝΗΣ"
// or
let v2 = ucase("Γιάννης");
var=strvar.lcase()Convert to lower case
let v1 = "ΓΙΆΝΝΗΣ"_var.lcase(); // "γιάννης"
// or
let v2 = lcase("ΓΙΆΝΝΗΣ");
var=strvar.tcase()

Convert to title case.

Returns: Original source string with the first letter of each word is capitalised.
let v1 = "γιάννης παππάς"_var.tcase(); // "Γιάννης Παππάς"
// or
let v2 = tcase("γιάννης παππάς");
var=strvar.fcase()

Convert to folded case.

Returns the source string standardised in a way to enable consistent indexing and searching,

Case folding is the process of converting text to a case independent representation.

https://www.w3.org/International/wiki/Case_folding

Accents can be significant. As in French cote, coté, côte and côté.

Case folding is not locale-dependent.
let v1 = "Grüßen"_var.fcase(); // "grüssen"
// or
let v2 = tcase("Grüßen");
var=strvar.normalize()

Replace Unicode character sequences with their standardised NFC form.

Unicode normalization is the process of converting Unicode strings to a standard form, making them binary comparable and suitable for text processing and comparison. It is an important part of Unicode text processing.

For example, Unicode character "é" can be represented by either a single Unicode character, which is Unicode Code Point (\u00E9" - Latin Small Letter E with Acute), or a combination of two Unicode code points i.e. the ASCII letter "e" and a combining acute accent (Unicode Code Point "\u0301"). Unicode NFC definition converts the pair of code points to the single code point.

Normalization is not locale-dependent.
let v1 = "cafe\u0301"_var.normalize(); // "caf\u00E9" // "café"
// or
let v2 = normalize("cafe\u0301");
var=strvar.invert()

Simple reversible disguising of string text.

It works by treating the string as UTF8 encoded Unicode code points and inverting the first 8 bits of their Unicode Code Points.

Returns: A string.

invert(invert()) returns to the original text.

ASCII bytes become multibyte UTF-8 so string sizes increase.

Inverted characters remain on their original Unicode Code Page but are jumbled up.

Non-existant Unicode Code Points may be created but UTF8 encoding remains valid.
let v1 = "abc"_var.invert(); // "\xC2" "\x9E" "\xC2" "\x9D" "\xC2" "\x9C"
// or
let v2 = invert("abc");
var=strvar.lower()

Reduce all types of field mark chars by one level.

Convert all FM to VM, VM to SM etc.

Returns: The converted string.

Note that subtext ST chars are not converted because they are already the lowest level.

String size remains identical.
let v1 = "a1^b2^c3"_var.lower(); // "a1]b2]c3"_var
// or
let v2 = lower("a1^b2^c3"_var);
var=strvar.raise()

Increase all types of field mark chars by one level.

Convert all VM to FM, SM to VM etc.

Returns: The converted string.

The record mark char RM is not converted because it is already the highest level.

String size remains identical.
let v1 = "a1]b2]c3"_var.raise(); // "a1^b2^c3"_var
// or
let v2 = "a1]b2]c3"_var;
var=strvar.crop()Remove any redundant FM, VM etc. chars (Trailing FM; VM before FM etc.)
let v1 = "a1^b2]]^c3^^"_var.crop(); // "a1^b2^c3"_var
// or
let v2 = crop("a1^b2]]^c3^^"_var);
var=strvar.quote()Wrap in double quotes.
let v1 = "abc"_var.quote(); // "\"abc\""
// or
let v2 = quote("abc");
var=strvar.squote()Wrap in single quotes.
let v1 = "abc"_var.squote(); // "'abc'"
// or
let v2 = squote("abc");
var=strvar.unquote()Remove one pair of surrounding double or single quotes.
let v1 = "'abc'"_var.unquote(); // "abc"
// or
let v2 = unquote("'abc'");
var=strvar.trim(trimchars = " ")

Remove all leading, trailing and excessive inner bytes.

trimchars: The chars (bytes) to remove. The default is space.
let v1 = "␣␣a1␣␣b2␣c3␣␣"_var.trim(); // "a1␣b2␣c3"
// or
let v2 = trim("␣␣a1␣␣b2␣c3␣␣");
var=strvar.trimfirst(trimchars = " ")Ditto but only leading.
let v1 = "␣␣a1␣␣b2␣c3␣␣"_var.trimfirst(); // "a1␣␣b2␣c3␣␣"
// or
let v2 = trimfirst("␣␣a1␣␣b2␣c3␣␣");
var=strvar.trimlast(trimchars = " ")Ditto but only trailing.
let v1 = "␣␣a1␣␣b2␣c3␣␣"_var.trimlast(); // "␣␣a1␣␣b2␣c3"
// or
let v2 = trimlast("␣␣a1␣␣b2␣c3␣␣");
var=strvar.trimboth(trimchars = " ")Ditto but only leading and trailing, not inner.
let v1 = "␣␣a1␣␣b2␣c3␣␣"_var.trimboth(); // "a1␣␣b2␣c3"
// or
let v2 = trimboth("␣␣a1␣␣b2␣c3␣␣");
var=strvar.first()

Get the first char of a string.

Returns: A char, or "" if empty.

Equivalent to var.substr(1,length) or var[1, length] in Pick OS
let v1 = "abc"_var.first(); // "a"
// or
let v2 = first("abc");
var=strvar.last()

Get the last char of a string.

Returns: A char, or "" if empty.

Equivalent to var.substr(-1, 1) or var[-1, 1] in Pick OS
let v1 = "abc"_var.last(); // "c"
// or
let v2 = last("abc");
var=strvar.first(std::size_t length)

Get the first n chars of a source string.

length: The number of chars (bytes) to get.

Returns: A string of up to n chars.

Equivalent to var.substr(1, length) or var[1, length] in Pick OS
let v1 = "abc"_var.first(2); // "ab"
// or
let v2 = first("abc", 2);
var=strvar.last(std::size_t length)

Extract up to length trailing chars

Equivalent to var.substr(-length, length) or var[-length, length] in Pick OS
let v1 = "abc"_var.last(2); // "bc"
// or
let v2 = last("abc", 2);
var=strvar.cut(length)

Remove n chars (bytes) from the source string.

length: Positive to remove first n chars or negative to remove the last n chars.

If the absolute value of length is >= the number of chars in the source string then all chars will be removed.

Equivalent to var.substr(length) or var[1, length] = "" in Pick OS
let v1 = "abcd"_var.cut(2); // "cd"
// or
let v2 = cut("abcd", 2);
var=strvar.paste(pos1, length, replacestr)

Insert a substr at an given position after removing a given number of chars.

pos1: 0 or 1 : Remove length chars from the beginning and insert at the beginning.

pos1: > than the length of the source string. Insert after the last char.

pos1: -1 : Remove up to length chars before inserting.Insert on or before the last char.

pos1: -2 : Insert on or before the penultimate char.

Equivalent to var[pos1, length] = substr in Pick OS
let v1 = "abcd"_var.paste(2, 2, "XYZ"); // "aXYZd"
// or
let v2 = paste("abcd", 2, 2, "XYZ");
var=strvar.paste(pos1, insertstr)

Insert text at char position without overwriting any following chars

Equivalent to var[pos1, 0] = substr in Pick OS
let v1 = "abcd"_var.paste(2, "XYZ"); // "aXYZbcd"
// or
let v2 = paste("abcd", 2, "XYZ");
var=strvar.prefix(insertstr)

Insert text at the beginning

Equivalent to var[0, 0] = substr in Pick OS
let v1 = "abc"_var.prefix("XYZ"); // "XYZabc"
// or
let v2 = prefix("abc", "XYZ");
var=strvar.append(appendable, ...)Append anything at the end of a string
let v1 = "abc"_var.append(" is ", 10, " ok", '.'); // "abc is 10 ok."
// or
let v2 = append("abc", " is ", 10, " ok", '.');
var=strvar.pop()

Remove one trailing char.

Equivalent to var[-1, 1] = "" in Pick OS
let v1 = "abc"_var.pop(); // "ab"
// or
let v2 = pop("abc");
var=strvar.field(delimiter, fieldnx = 1, nfieldsx = 1)

Copies one or more consecutive fields from a string given a delimiter

delimiter: A Unicode character.

fieldno: The first field is 1, the last field is -1.

Returns: A substring
let v1 = "aa*bb*cc"_var.field("*", 2); // "bb"
// or
let v2 = field("aa*bb*cc", "*", 2);
let v1 = "aa*bb*cc"_var.field("*", -1); // "cc"
// or
let v2 = field("aa*bb*cc", "*", -1);
var=strvar.fieldstore(separator, fieldno, nfields, replacement)

fieldstore() replaces, inserts or deletes subfields in a string.

fieldno: The field number to replace or, if not 1, the field number to start at. Negative fieldno counts backwards from the last field.

nfields: The number of fields to replace or, if negative, the number of fields to delete first. Can be 0 to cause simple insertion of fields.

replacement: A string that is the replacement field or fields.

Returns: A modified copy of the original string.

There is no way to simply delete n fields because the replacement argument cannot be omitted, however one can achieve the same result by replacing n+1 fields with the n+1th field.

The replacement can contain multiple fields itself. If replacing n fields and the replacement contains < n fields then the remaining fields become "". Conversely, if the replacement contains more fields than are required, they are discarded.
let v1 = "aa,bb,cc,dd,ee"_var.fieldstore(",", 2, 3, "11,22"); // "aa,11,22,,ee"
// or
let v2 = fieldstore("aa,bb,cc,dd,ee", ",", 2, 3, "11,22");
If nfields is 0 then insert the replacement field(s) before fieldno
let v1 = "aa,bb,cc,dd,ee"_var.fieldstore(",", 2, 0, "11,22"); // "aa,11,22,bb,cc,dd,ee"
If nfields is negative then delete abs(n) fields before inserting whatever fields the replacement has.
let v1 = "aa,bb,cc,dd,ee"_var.fieldstore(",", 2, -2, "11"); // "aa,11,dd,ee"
If nfields exceeds the number of fields in the input then additional empty fields are added.
let v1 = "aa,bb,cc"_var.fieldstore(",", 6, 2, "11"); // "aa,bb,cc,,,11,"
var=strvar.substr(pos1, length)

substr version 1.

Copies a substr of length chars from a given a starting char position.

Returns: A substr or "".

pos1: The char position to start at. If negative then start from a position counting backwards from the last char

length: The number of chars to copy. If negative then copy backwards. This reverses the order of the chars in the returned substr.

Equivalent to var[start, length] in Pick OS

Not Unicode friendly.
let v1 = "abcd"_var.substr(2, 2); // "bc"
// or
let v2 = substr("abcd", 2, 2);
If pos1 is negative then start counting backwards from the last char
let v1 = "abcd"_var.substr(-3, 2); // "bc"
// or
let v2 = substr("abcd", -3, 2);
If length is negative then work backwards and return chars reversed
let v1 = "abcd"_var.substr(3, -2); // "cb"
// or
let v2 = substr("abcd", 3, -2); // "cb"
var=strvar.b(pos1, length)Abbreviated alias of substr version 1.
var=strvar.substr(pos1)

substr version 2.

Copies a substr from a given char position up to the end of the source string

Returns: A substr or "".

pos1: The char position to start at. If negative then start from a position counting backwards from the last char

Equivalent to var[pos1, 9999999] in Pick OS

Partially Unicode friendly but pos1 is in chars.
let v1 = "abcd"_var.substr(2); // "bcd"
// or
let v2 = substr("abcd", 2);
var=strvar.b(pos1)Shorthand alias of substr version 2.
var=strvar.substr(pos1, delimiterchars, out pos2)

substr version 3.

Copies a substr from a given char position up to (but excluding) any one of some given delimiter chars

Returns: A substr or "".

pos1: [in] The position of the first char to copy. Negative positions count backwards from the last char of the string.

pos2: [out] The position of the next delimiter char, or one char position after the end of the source string if no subsequent delimiter chars are found.

COL2: is a predefined variable that can be used for pos2 instead of declaring a variable.

An empty string may be returned if pos1 [in] points to one of the delimiter chars or points beyond the end of the source string.

Equivalent to var[pos1, ",."] in Pick OS (non-numeric length).

Works with any encoding including UTF8 for the source string but the delimiter chars are bytes.

Add 1 to pos2 to skip over the next delimiter char to copy the next substr

Works with any encoding including UTF8 for the source string but the delimiter chars are bytes.

This function is similar to std::string::find_first_of but that function only returns pos2.
var pos1 = 4;
let v1 = "12,45 78"_var.substr(pos1, ", ", COL2);  // v1 -> "45" // COL2 -> 6 // 6 is the position of the next delimiter char found.
// or
let v2 = substr("12,45 78", COL2 + 1, ", ", COL2); // v2 -> "78" // COL2 -> 9 // 9 is one after the end of the string meaning that none of the delimiter chars were found.
var=strvar.b(pos1, delimiterchars, out pos2)Shorthand alias of substr version 3.
var=strvar.substr2(io pos1, out delimiterno)

substr version 4.

Copies a substr from a given char position up to (but excluding) the next field mark char (RM, FM, VM, SM, TM, ST).

Returns: A substr or "".

pos1: [in] The position of the first char to copy. Negative positions count backwards from the last char of the string.

pos1: [out] The position of the first char of the next substr after whatever field mark char is found, or one char position after the end of the source string if no subsequent field mark char is found.

field_mark_no: [out] A number (1-6) indicating which of the standard field mark chars was found, or 0 if not.

An empty string may be returned if the pos1 [in] points to one of the field marks or beyond the end of the source string.

pos1 [out] is correctly positioned to copy the next substr.

Works with any encoding including UTF8. Was called "remove" in Pick OS.

The equivalent in Pick OS was the statement "Remove variable From string At column Setting flag"

...

This function is valuable for high performance processing of dynamic arrays.

It is notably used in "list" to print parallel columns of mixed combinations of multivalues/subvalues and text marks correctly lined up mv to mv, sv to sv, tm to tm even when particular values, subvalues and text fragments are missing from particular columns.

It is similar to version 3 of substr - substr(pos1, delimiterchars, pos2) except that in this version the delimiter chars are hard coded as the standard field mark chars (RM, FM, VM, SM, TM, ST) and it returns the first char position of the next substr, not the char position of the next field mark char.
var pos1 = 4, field_mark_no;
let v1 = "12^45^78"_var.substr2(pos1, field_mark_no);  // "45" // pos1 -> 7 // field_mark_no -> 2 // field_mark_no 2 means that a FM was found.
// or
let v2 = substr2("12^45^78"_var, pos1, field_mark_no); // "78" // pos1 -> 9 // field_mark_no -> 0 // field_mark_no 0 means that none of the standard field marks were found.
var=strvar.b2(io pos1, out field_mark_no)Shorthand alias of substr version 4.
var=strvar.convert(fromchars, tochars)

Convert or delete chars one for one to other chars

from_chars: chars to convert. If longer than to_chars then delete those characters instead of converting them.

to_chars: chars to convert to

Not UTF8 compatible.
let v1 = "abcde"_var.convert("aZd", "XY"); // "Xbce" // a is replaced and d is removed
// or
let v2 = convert("abcde", "aZd", "XY");
var=strvar.textconvert(fromchars, tochars)Ditto for Unicode code points.
let v1 = "a🤡b😀c🌍d"_var.textconvert("🤡😀", "👋"); // "a👋bc🌍d"
// or
let v2 = textconvert("a🤡b😀c🌍d", "🤡😀", "👋");
var=strvar.replace(fromstr, tostr)

Replace all occurrences of one substr with another.

Case sensitive.
let v1 = "Abc.Abc"_var.replace("bc", "X"); // "AX.AX"
// or
let v2 = replace("Abc Abc", "bc", "X");
var=strvar.replace(regex, replacement_str)

Replace substrings using a regular expression.

regex: A regular expression created by rex() or _rex.

replacement_str: A literal to replace all matched substrings.

The replacement string can include the following special replacement patterns:

Pattern Inserts

$$ Inserts a "$".

$& Inserts the matched substring. Equivalent to $0.

$` Inserts the portion of the string that precedes the matched substring.

$' Inserts the portion of the string that follows the matched substring.

$n Inserts the nth (1-indexed) capturing group where n is a positive integer less than 100.
let v1 = "A a B b"_var.replace("[A-Z]"_rex, "'$0'"); // "'A' a 'B' b"
// or
let v2 = replace("A a B b", "[A-Z]"_rex, "'$0'");
var=strvar.replace(regex, SomeFunction(match_str))

Replace substrings using a regular expression and a custom function.

Allows very complex string conversions.

SomeFunction: Must return a var. Can be an inline anonymous lambda function.

e.g. [](auto match_str) {return match_str;} // Does nothing.

match_str: Text of a single match. If regex groups are used, match_str.f(1, 1) is the whole match, match_str.f(1, 2) is the first group, etc.
// Decode hex escape codes.
var v1 = R"(--\0x3B--\0x2F--)";                                 // Hex escape codes.
v1.replacer(
    R"(\\0x[0-9a-fA-F]{2,2})"_rex,                              // Finds \0xFF.
    [](auto match_str) {return match_str.cut(3).iconv("HEX");}  // Decodes to a char.
);
assert(v1 == "--;--/--");

// Reformat dates using groups.
var v2 = "Date: 03-15-2025";
v2.replacer(
    R"((\d{2})-(\d{2})-(\d{4}))"_rex,
    [](auto match_str) {return match_str.f(1, 4) ^ "-" ^ match_str.f(1, 2) ^ "-" ^ match_str.f(1, 3);}
);
assert(v2 == "Date: 2025-03-15");
var=strvar.unique()Remove duplicate fields in an FM or VM etc. separated list
let v1 = "a1^b2^a1^c2"_var.unique(); // "a1^b2^c2"_var
// or
let v2 = unique("a1^b2^a1^c2"_var);
var=strvar.sort(delimiter = FM)

Reorder fields in an FM or VM etc. separated list in ascending order

Numeric data:
let v1 = "20^10^2^1^1.1"_var.sort(); // "1^1.1^2^10^20"_var
// or
let v2 = sort("20^10^2^1^1.1"_var);
Alphabetic data:
let v1 = "b1^a1^c20^c10^c2^c1^b2"_var.sort(); // "a1^b1^b2^c1^c10^c2^c20"_var
// or
let v2 = sort("b1^a1^c20^c10^c2^c1^b2"_var);
var=strvar.reverse(delimiter = FM)Reorder fields in an FM or VM etc. separated list in descending order
let v1 = "20^10^2^1^1.1"_var.reverse(); // "1.1^1^2^10^20"_var
// or
let v2 = reverse("20^10^2^1^1.1"_var);
var=strvar.shuffle(delimiter = FM)Randomise the order of fields in an FM, VM separated list
let v1 = "20^10^2^1^1.1"_var.shuffle(); /// e.g. "2^1^20^1.1^10" (random order depending on initrand())
// or
let v2 = shuffle("20^10^2^1^1.1"_var);
var=strvar.parse(char sepchar = ' ')

Split a delimited string with embedded quotes into a dynamic array.

Can be used to process CSV data.

Replaces separator chars with FM chars except inside double or single quotes and ignoring escaped quotes \" \'
let v1 = "abc,\"def,\"123\" fgh\",12.34"_var.parse(','); // "abc^\"def,\"123\" fgh\"^12.34"_var
// or
let v2 = parse("abc,\"def,\"123\" fgh\",12.34", ',');
dim=strvar.split(delimiter = FM)

Split a delimited string into a dim array.

The delimiter can be multibyte Unicode.

Returns: A dim array.
dim d1 = "a^b^c"_var.split(); // A dimensioned array with three elements (vars)
// or
dim d2 = split("a^b^c"_var);
var=strvar.fieldstore(delimiter, fieldno, nfields, replacement)
String Mutation - Standalone Commands
Use Function Description
strvar.ucaser()

Upper case

All string mutators follow the same pattern as ucaser.
See the non-mutating functions for details.
var v1 = "abc";
v1.ucaser(); // "ABC"
// or
ucaser(v1);
strvar.lcaser()
strvar.tcaser()
strvar.fcaser()
strvar.normalizer()
strvar.inverter()
strvar.quoter()
strvar.squoter()
strvar.unquoter()
strvar.lowerer()
strvar.raiser()
strvar.cropper()
strvar.trimmer(trimchars = " ")
strvar.trimmerfirst(trimchars = " ")
strvar.trimmerlast(trimchars = " ")
strvar.trimmerboth(trimchars = " ")
strvar.firster()
strvar.laster()
strvar.firster(std::size_t length)
strvar.laster(std::size_t length)
strvar.cutter(length)
strvar.paster(pos1, length, insertstr)
strvar.paster(pos1, insertstr)
strvar.prefixer(insertstr)
strvar.appender(appendable, ...)
strvar.popper()
strvar.fieldstorer(delimiter, fieldno, nfields, replacement)
strvar.substrer(pos1, length)
strvar.substrer(pos1)
strvar.converter(from_chars, to_chars)
strvar.textconverter(from_characters, to_characters)
strvar.replacer(regex, tostr)
strvar.replacer(regex, SomeFunction(match_str))
strvar.replacer(fromstr, tostr)
strvar.uniquer()
strvar.sorter(delimiter = FM)
strvar.reverser(delimiter = FM)
strvar.shuffler(delimiter = FM)
strvar.parser(char sepchar = ' ')
I/O Conversion
Use Function Description
var=var.oconv(convstr)

Converts internal data to output external display format according to a given conversion code or pattern

If the internal data is invalid and cannot be converted then most conversions return the ORIGINAL data unconverted

Throws a runtime error VarNotImplemented if convstr is invalid

See [[#ICONV/OCONV PATTERNS]]
let v1 = var(30123).oconv("D/E"); // "21/06/2050"
// or
let v2 = oconv(30123, "D/E");
var=var.iconv(convstr)

Converts external data to internal format according to a given conversion code or pattern

If the external data is invalid and cannot be converted then most conversions return the EMPTY STRING ""

Throws a runtime error VarNotImplemented if convstr is invalid

See [[#ICONV/OCONV PATTERNS]]
let v1 = "21 JUN 2050"_var.iconv("D/E"); // 30123
// or
let v2 = iconv("21 JUN 2050", "D/E");
var=var.format(fmt_str, args, ...)

Classic format function in printf style

vars can be formatted either with C++ format codes e.g. {:_>8.2f}

or with exodus oconv codes e.g. {::MD20P|R(_)#8} as in the below example.
let v1 = var(12.345).format("'{:_>8.2f}'"); // "'___12.35'"
let v2 = var(12.345).format("'{::MD20P|R(_)#8}'");
// or
var v3 = format("'{:_>8.2f}'", var(12.345)); // "'___12.35'"
var v4 = format("'{::MD20P|R(_)#8}'", var(12.345));
var=strvar.from_codepage(codepage)

Converts from codepage encoded text to UTF-8 encoded exodus text

e.g. Codepage "CP1124" (Ukrainian).

Use Linux command "iconv -l" for complete list of code pages and encodings.
let v1 = "\xa4"_var.from_codepage("CP1124"); // "Є"
// or
let v2 = from_codepage("\xa4", "CP1124");
// U+0404 Cyrillic Capital Letter Ukrainian Ie Unicode character
var=strvar.to_codepage(codepage)Converts to codepage encoded text from exodus UTF-8 encoded text
let v1 = "Є"_var.to_codepage("CP1124").oconv("HEX"); // "A4"
// or
let v2 = to_codepage("Є", "CP1124").oconv("HEX");
Dynamic Array Functions
Use Function Description
var=strvar.f(fieldno, valueno = 0, subvalueno = 0)

f() is a highly abbreviated alias for the Pick OS field/value/subvalue extract() function.

"f()" can be thought of as "field" although the function can extract values and subvalues as well.

The convenient Pick OS angle bracket syntax for field extraction (e.g. xxx<20>) is not available in C++.

The abbreviated exodus field extraction function (e.g. xxx.f(20)) is provided instead since field access is extremely heavily used in source code.
let v1 = "f1^f2v1]f2v2]f2v3^f2"_var;
let v2 = v1.f(2, 2); // "f2v2"
var=strvar.extract(fieldno, valueno = 0, subvalueno = 0)Extract a specific field, value or subvalue from a dynamic array.
let v1 = "f1^f2v1]f2v2]f2v3^f2"_var;
let v2 = v1.extract(2, 2); // "f2v2"
//
// For brevity the function alias "f()" (standing for "field") is normally used instead of "extract()" as follows:
var v3 = v1.f(2, 2);
var=strvar.update(fieldno, valueno, subvalueno, replacement)

Same as var.updater() function but returns a new string instead of updating a variable in place.
Rarely used.

"update()" was called "replace()" in Pick OS/Basic.
var=strvar.update(fieldno, valueno, replacement)Ditto for a specific multivalue
var=strvar.update(fieldno, replacement)Ditto for a specific field
var=strvar.insert(fieldno, valueno, subvalueno, insertion)Same as var.inserter() function but returns a new string instead of updating a variable in place.
var=strvar.insert(fieldno, valueno, insertion)Ditto for a specific multivalue
var=strvar.insert(fieldno, insertion)Ditto for a specific field
var=strvar.remove(fieldno, valueno = 0, subvalueno = 0)

Same as var.remover() function but returns a new string instead of updating a variable in place.

"remove()" was called "delete()" in Pick OS/Basic.
Dynamic Array Filters
Use Function Description
var=strvar.sum()Sum up multiple values into one higher level
let v1 = "1]2]3^4]5]6"_var.sum(); // "6^15"_var
// or
let v2 = sum("1]2]3^4]5]6"_var);
var=strvar.sumall()Sum up all levels into a single figure
let v1 = "1]2]3^4]5]6"_var.sumall(); // 21
// or
let v2 = sumall("1]2]3^4]5]6"_var);
var=strvar.sum(delimiter)Ditto allowing commas etc.
let v1 = "10,20,30"_var.sum(","); // 60
// or
let v2 = sum("10,20,30", ",");
var=strvar.mv(opcode, var2)Binary ops (+, -, *, /) in parallel on multiple values
let v1 = "10]20]30"_var.mv("+","2]3]4"_var); // "12]23]34"_var
Dynamic Array Mutators Standalone Commands
Use Function Description
strvar.updater(fieldno, replacement)Replace a specific field in a dynamic array
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.updater(2, "X"); // "f1^X^f3"_var
// or
v1(2) = "X"; /// Easiest.
// or
updater(v1, 2, "X");
strvar.updater(fieldno, valueno, replacement)Replace a specific value of a specific field in a dynamic array.
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.updater(2, 2, "X"); // "f1^v1]X^f3"_var
// or
v1(2, 2) = "X"; /// Easiest.
// or
updater(v1, 2, 2, "X");
strvar.updater(fieldno, valueno, subvalueno, replacement)Replace a specific subvalue of a specific value of a specific field in a dynamic array.
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.updater(2, 2, 2, "X"); // "f1^v1]v2}X}s3^f3"_var
// or
v1(2, 2, 2) = "X"; /// Easiest.
// or
updater(v1, 2, 2, 2, "X");
strvar.inserter(fieldno, insertion)Insert a specific field in a dynamic array, moving all other fields up.
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.inserter(2, "X"); // "f1^X^v1]v2}s2}s3^f3"_var
// or
inserter(v1, 2, "X");
strvar.inserter(fieldno, valueno, insertion)Ditto for a specific value in a specific field, moving all other values up.
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.inserter(2, 2, "X"); // "f1^v1]X]v2}s2}s3^f3"_var
// or
inserter(v1, 2, 2, "X");
strvar.inserter(fieldno, valueno, subvalueno, insertion)Ditto for a specific subvalue in a dynamic array, moving all other subvalues up.
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.inserter(2, 2, 2, "X"); // "f1^v1]v2}X}s2}s3^f3"_var
// or
v1.inserter(2, 2, 2, "X");
strvar.remover(fieldno, valueno = 0, subvalueno = 0)Remove a specific field (or value, or subvalue) from a dynamic array, moving all other fields (or values, or subvalues) down.
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.remover(2, 2); // "f1^v1^f3"_var
// or
remover(v1, 2, 2);
Use Function Description
var=strvar.locate(target)

locate() with only the target substr argument provided searches unordered values separated by any of the field mark chars.

Returns: The field, value, subvalue etc. number if found or 0 if not.

Searching for empty fields, values etc. (i.e. "") will work. Locating "" in "]yy" will return 1, in "xx]]zz" 2, and in "xx]yy]" 3, however, locating "" in "xx" will return 0 because there is conceptually no empty value in "xx". Locate "" in "" will return 1.
if ("UK^US^UA"_var.locate("US")) ... ok // 2
// or
if (locate("US", "UK^US^UA"_var)) ... ok
ifstrvar.locate(target, out valueno)

locate() with only the target substr provided and setting returned searches unordered values separated by any type of field mark chars.

Returns: True if found

Setting: Field, value, subvalue etc. number if found or the max number + 1 if not. Suitable for additiom of new values
var setting;
if ("UK]US]UA"_var.locate("US", setting)) ... ok // setting -> 2
// or
if (locate("US", "UK]US]UA"_var, setting)) ... ok
ifstrvar.locate(target, out setting, fieldno, valueno = 0)

locate() the target in unordered fields if fieldno is 0, or values if a fieldno is specified, or subvalues if the valueno argument is provided.

Returns: True if found and with the field, value or subvalue number in setting.

Returns: False if not found and with the max field, value or subvalue number found + 1 in setting. Suitable for replacement of new fields, values or subvalues.
var setting;
if ("f1^f2v1]f2v2]s1}s2}s3}s4^f3^f4"_var.locate("s4", setting, 2, 3)) ... ok // setting -> 4 // returns true
ifstrvar.locateby(ordercode, target, out valueno)

locateby() without fieldno or valueno arguments searches ordered values separated by VM chars.

The order code can be AL, DL, AR, DR meaning Ascending Left, Descending Right, Ascending Right, Ascending Left.

Left is used to indicate alphabetic order where 10 < 2.

Right is used to indicate numeric order where 10 > 2.

Data must be in the correct order for searching to work properly.

Returns: True if found.

In case the target is not exactly found then the correct value no for inserting the target is returned in setting.
var valueno; if ("aaa]bbb]ccc"_var.locateby("AL", "bb", valueno)) ... // valueno -> 2 // returns false and valueno = where it could be correctly inserted.
ifstrvar.locateby(ordercode, target, out setting, fieldno, valueno = 0)locateby() ordered as above but in fields if fieldno is 0, or values in a specific fieldno, or subvalues in a specific valueno.
var setting;
if ("f1^f2^aaa]bbb]ccc^f4"_var.locateby("AL", "bb", setting, 3)) ... // setting -> 2 // return false and where it could be correctly inserted.
ifstrvar.locateusing(usingchar, target)locate() a target substr in the whole unordered string using a given delimiter char returning true if found.
if ("AB,EF,CD"_var.locateusing(",", "EF")) ... ok
ifstrvar.locateusing(usingchar, target, out setting, fieldno = 0, valueno = 0, subvalueno = 0)

locate() the target in a specific field, value or subvalue using a specified delimiter and unordered data

Returns: True If found and returns in setting the number of the delimited field found.

Returns: False if not found and returns in setting the maximum number of delimited fields + 1 if not found.

This is similar to the main locate command but the delimiter char can be specified e.g. a comma or TM etc.
var setting;
if ("f1^f2^f3c1,f3c2,f3c3^f4"_var.locateusing(",", "f3c2", setting, 3)) ... ok // setting -> 2 // returns true
ifstrvar.locatebyusing(ordercode, usingchar, target, out setting, fieldno = 0, valueno = 0, subvalueno = 0)

locatebyusing() supports all the above features in a single function.

Returns: True if found.
Database Access
Use Function Description
ifconn.connect(conninfo = "")

For all db operations, the operative var can either be a db connection created with dbconnect() or be any var and a default connection will be established on the fly.

The db connection string (conninfo) parameters are merged from the following places in descending priority.

1. Provided in connect()'s conninfo argument. See 4. for the complete list of parameters.

2. Any environment variables EXO_HOST EXO_PORT EXO_USER EXO_DATA EXO_PASS EXO_TIME

3. Any parameters found in a configuration file at ~/.config/exodus/exodus.cfg

4. The default conninfo is "host=127.0.0.1 port=5432 dbname=exodus user=exodus password=somesillysecret connect_timeout=10"

Setting environment variable EXO_DBTRACE=1 will cause tracing of db interface including SQL commands.
let conninfo = "dbname=exodus user=exodus password=somesillysecret";
if (not conn.connect(conninfo)) ...;
// or
if (not connect()) ...
// or
if (not connect("exodus")) ...
ifconn.attach(filenames)

"attach" causes the given filenames to be associated with a specific connection for the remainder of the session.

It is not necessary to attach files before opening them.

Attachments can changed by calling attach() or open() on a different connection or they can be removed by calling detach().

var: Defaults to the default connection.

filenames: FM separated list.

Returns: false if any filename does not exist and cannot be opened on the given connection. All filenames that can be opened on the conneciton are attached even if some cannot.

Internally, attach merely opens each filename on the given connection causing them to be added to an internal cache.
let filenames = "xo_clients^dict.xo_clients"_var, conn = "exodus";
if (conn.attach(filenames)) ... ok
// or
if (attach(filenames)) ... ok
conn.detach(filenames)

Removes files from the internal cache created by previous open() and attach() calls.

var: Defaults to the default connection.

filenames: FM separated list.

ifconn.begintrans()Begin a db transaction.
if (not conn.begintrans()) ...
// or
if (not begintrans()) ...
ifconn.statustrans()Check if a db transaction is in progress.
if (conn.statustrans()) ... ok
// or
if (statustrans()) ... ok
ifconn.rollbacktrans()Rollback a db transaction.
if (conn.rollbacktrans()) ... ok
// or
if (rollbacktrans()) ... ok
ifconn.committrans()

Commit a db transaction.

Returns: True if successfully committed or if there was no transaction in progress, otherwise false.
if (conn.committrans()) ... ok
// or
if (committrans()) ... ok
ifconn.sqlexec(sqlcmd)

Execute an sql command.

Returns: True if there was no sql error otherwise lasterror() returns a detailed error message.
if (conn.sqlexec("select 1")) ... ok
// or
if (sqlexec("select 1")) ... ok
ifconn.sqlexec(sqlcmd, io response)

Execute an SQL command and capture the response.

Returns: True if there was no sql error otherwise response contains a detailed error message.

response: Any rows and columns returned are separated by RM and FM respectively. The first row is the column names.

Recommended: Don't use sql directly unless you must to manage or configure a database.
let sqlcmd = "select 'xxx' as col1, 'yyy' as col2";
var response;
if (conn.sqlexec(sqlcmd, response)) ... ok // response -> "col1^col2\x1fxxx^yyy"_var /// \x1f is the Record Mark (RM) char. The backtick char is used here by gendoc to deliminate source code.
// or
if (sqlexec(sqlcmd, response)) ... ok
conn.disconnect()Closes db connection and frees process resources both locally and in the database server.
conn.disconnect();
// or
disconnect();
conn.disconnectall()

Closes all connections and frees process resources both locally and in the database server(s).

All connections are closed automatically when a process terminates.
conn.disconnectall();
// or
disconnectall();
var=var::lasterror() Returns: The last os or db error message.
var v1 = var::lasterror();
// or
var v2 = lasterror();
var::loglasterror(source = "")

Log the last os or db error message.

Output: to stdlog

Prefixes the output with source if provided.
var::loglasterror("main:");
// or
loglasterror("main:");
Database Management
Use Function Description
ifconn.dbcreate(new_dbname, old_dbname = "")

Create a named database on a particular connection.

The target database cannot already exist.

Optionally copies an existing database from the same connection and which cannot have any current connections.
var conn = "exodus";
if (not dbdelete("xo_gendoc_testdb")) {}; // Cleanup first
if (conn.dbcreate("xo_gendoc_testdb")) ... ok
// or
if (dbcreate("xo_gendoc_testdb")) ...
ifconn.dbcopy(from_dbname, to_dbname)

Create a named database as a copy of an existing database.

The target database cannot already exist.

The source database must exist on the same connection and cannot have any current connections.
var conn = "exodus";
if (not dbdelete("xo_gendoc_testdb2")) {}; // Cleanup first
if (conn.dbcopy("xo_gendoc_testdb", "xo_gendoc_testdb2")) ... ok
// or
if (dbcopy("xo_gendoc_testdb", "xo_gendoc_testdb2")) ...
var=conn.dblist() Returns: A list of available databases on a particular connection.
let v1 = conn.dblist();
// or
let v2 = dblist();
ifconn.dbdelete(dbname)

Delete (drop) a named database.

The target database must exist and cannot have any current connections.
var conn = "exodus";
if (conn.dbdelete("xo_gendoc_testdb2")) ... ok
// or
if (dbdelete("xo_gendoc_testdb2")) ...
ifconn.createfile(filename)

Create a named db file.

filenames ending with "_temp" only last until the connection is closed.
let filename = "xo_gendoc_temp", conn = "exodus";
if (conn.createfile(filename)) ... ok
// or
if (createfile(filename)) ...
ifconn.renamefile(filename, newfilename)Rename a db file.
let conn = "exodus", filename = "xo_gendoc_temp", new_filename = "xo_gendoc_temp2";
if (conn.renamefile(filename, new_filename)) ... ok
// or
if (renamefile(filename, new_filename)) ...
var=conn.listfiles() Returns: A list of all files in a database
var conn = "exodus";
if (not conn.listfiles()) ...
// or
if (not listfiles()) ...
ifconn.clearfile(filename)Delete all records in a db file
let conn = "exodus", filename = "xo_gendoc_temp2";
if (not conn.clearfile(filename)) ...
// or
if (not clearfile(filename)) ...
ifconn.deletefile(filename)Delete a db file
let conn = "exodus", filename = "xo_gendoc_temp2";
if (conn.deletefile(filename)) ... ok
// or
if (deletefile(filename)) ...
var=conn_or_file.reccount(filename = "")

Returns: The approx. number of records in a db file.

Might return -1 if not known.

Not very accurate inside transactions.
let conn = "exodus", filename = "xo_clients";
var nrecs1 = conn.reccount(filename);
// or
var nrecs2 = reccount(filename);
ifconn_or_file.flushindex(filename = "")

Calls db maintenance function for a file or all files.

This doesnt actually flush any indexes but does make sure that reccount() function is reasonably accurate.

Returns: True if successful otherwise false if not and with lasterror() set.
Database File I/O
Use Function Description
iffile.open(dbfilename, connection = "")

Opens a db file to a var which can be used in subsequent db function calls to access a specific file using a specific connection.

connection: If not specified and the filename is present in an internal cache of filenames and connections created by previous calls to open() or attach() then open() returns true. If it is not present in the cache then the default connection will be checked.

Returns: True if the filename was present in the cache OR if the db connection reports that the file is present.
var file, filename = "xo_clients";
if (not file.open(filename)) ...
// or
if (not open(filename to file)) ...
file.close()

Closes db file var

Does nothing currently since database file vars consume no resources
var file = "xo_clients";
file.close();
// or
close(file);
iffile.createindex(fieldname, dictfile = "")

Creates a secondary index for a given db file and field name.

The fieldname must exist in a dictionary file. The default dictionary is "dict." ^ filename.

Returns: False if the index cannot be created for any reason.

* Index already exists

* File does not exist

* The dictionary file does not have a record with a key of the given field name.

* The dictionary file does not exist. Default is "dict." ^ filename.

* The dictionary field defines a calculated field that uses an exodus function. Using a psql function is OK.
var filename = "xo_clients", fieldname = "DATE_CREATED";
if (not deleteindex("xo_clients", "DATE_CREATED")) {}; // Cleanup first
if (filename.createindex(fieldname)) ... ok
// or
if (createindex(filename, fieldname)) ...
var=file|conn.listindex(file_or_filename = "", fieldname = "")

Lists secondary indexes in a database or for a db file

Returns: False if the db file or fieldname are given and do not exist
var conn = "exodus";
if (conn.listindex()) ... ok // includes "xo_clients__date_created"
// or
if (listindex()) ... ok
iffile.deleteindex(fieldname)

Deletes a secondary index for a db file and field name.

Returns: False if the index cannot be deleted for any reason

* File does not exist

* Index does not already exists
var file = "xo_clients", fieldname = "DATE_CREATED";
if (file.deleteindex(fieldname)) ... ok
// or
if (deleteindex(file, fieldname)) ...
var=file.lock(key)

Places a metaphorical db lock on a particular record given a db file and key.

This is a advisory lock, not a physical lock, since it makes no restriction on the access or modification of data by other connections.

Neither the db file nor the record key need to actually exist since a lock is just a hash of the db file name and key combined.

If another connection attempts to place an identical lock on the same database it will be denied.

Locks can be removed by unlock() or unlockall() or will be automatically removed at the end of a transaction or when the connection is closed.

If the same process attempts to place an identical lock more than once it may be denied (if not in a transaction) or succeed but be ignored (if in a transaction).

Locks can be used to avoid processing a transaction simultaneously with another connection only to have one of them fail due to mutually updating the same records.

Returns::

* 0: Failure: Another connection has already placed the same lock.

* "" Failure: The lock has already been placed.

* 1: Success: A new lock has been placed.

* 2: Success: The lock has already been placed and the connection is in a transaction.
var file = "xo_clients", key = "1000";
if (file.lock(key)) ... ok
// or
if (lock(file, key)) ...
iffile.unlock(key)

Removes a db lock placed by the lock function.

Only locks placed on the specified connection can be removed.

Locks cannot be removed while a connection is in a transaction.

Returns: False if the lock is not present in a connection.
var file = "xo_clients", key = "1000";
if (file.unlock(key)) ... ok
// or
if (unlock(file, key)) ...
iffile.unlockall()

Removes all db locks placed by the lock function in the specified connection.

Locks cannot be removed while in a transaction.
var conn = "exodus";
if (not conn.unlockall()) ...
// or
if (not unlockall(conn)) ...
record.write(file, key)

Writes a record into a db file given a unique primary key.

Either inserts a new record or updates an existing record.

Returns: Nothing since writes always succeed.

Throws: VarDBException if the file does not exist. Like most db functions.

Any memory cached record is deleted.
let record = "Client GD^G^20855^30000^1001.00^20855.76539"_var;
let file = "xo_clients", key = "GD001";
//if (not "xo_clients"_var.deleterecord("GD001")) {}; // Cleanup first
record.write(file, key);
// or
write(record on file, key);
ifrecord.read(file, key)

Reads a record from a db file for a given key.

file: A db filename or a var opened to a db file.

key: The key of the record to be read.

Returns: False if the key doesnt exist

var: Contains the record if it exists or is unassigned if not.

A special case of the key being "%RECORDS%" results in a fictitious "record" being returned as an FM separated list of all the keys in the db file up to a maximum size of 4Mib, sorted in natural order.
var record;
let file = "xo_clients", key = "GD001";
if (not record.read(file, key)) ... // record -> "Client GD^G^20855^30000^1001.00^20855.76539"_var
// or
if (not read(record from file, key)) ...
iffile.deleterecord(key)

Deletes a record from a db file given a key.

Returns: False if the key doesnt exist

Any memory cached record is deleted.

deleterecord(in file), a one argument free function, is available that deletes multiple records using the currently active select list.
let file = "xo_clients", key = "GD001";
if (file.deleterecord(key)) ... ok
// or
//if (deleterecord(file, key)) ...
ifrecord.insertrecord(file, key)

Inserts a new record in a db file.

Returns: False if the key already exists

Any memory cached record is deleted.
let record = "Client GD^G^20855^30000^1001.00^20855.76539"_var;
let file = "xo_clients", key = "GD001";
if (record.insertrecord(file, key)) ... ok
// or
if (insertrecord(record on file, key)) ...
ifrecord.updaterecord(file, key)

Updates an existing record in a db file.

Returns: False if no record with the given key exists.

Any memory cached record is deleted.
let record = "Client GD^G^20855^30000^1001.00^20855.76539"_var;
let file = "xo_clients", key = "GD001";
if (not record.updaterecord(file, key)) ...
// or
if (not updaterecord(record on file, key)) ...
ifrecord.updatekey(key, newkey)

Updates the key of an existing record in a db file.

Returns: True if successful or false if no record with the given key exists, or a record with newkey already exists

Any memory cached records of either key are deleted.
let file = "xo_clients", key = "GD001", newkey = "GD002";
if (not file.updatekey(key, newkey)) ...
// or
if (not updatekey(file, newkey, key)) ... // Reverse the above change.
ifstrvar.readf(file, key, fieldno)"Read field" Same as read() but only returns a specific field number from the record.
var field, file = "xo_clients", key = "GD001", fieldno = 2;
if (not field.readf(file, key, fieldno)) ... // field -> "G"
// or
if (not readf(field from file, key, fieldno)) ...
strvar.writef(file, key, fieldno)"write field" Same as write() but only writes to a specific field number in the record
var field = "f3", file = "xo_clients", key = "1000", fieldno = 3;
field.writef(file, key, fieldno);
// or
writef(field on file, key, fieldno);
record.writec(file, key)

"Write cache" Writes a record and key into a memory cached "db file".

The actual database file is NOT updated.

writec() either updates an existing cache record if the key already exists or otherwise inserts a new record into the cache.

It always succeeds so no result code is returned.

Neither the db file nor the record key need to actually exist in the actual db.
let record = "Client XD^X^20855^30000^1001.00^20855.76539"_var;
let file = "xo_clients", key = "XD001";
record.writec(file, key);
// or
writec(record on file, key);
ifrecord.readc(file, key)

"Read cache" Same as "read() but first reads from a memory cache.

1. Tries to read from a memory cache. Returns true if successful.

2a. Tries to read from the actual db file and returns false if unsuccessful.

2b. Writes the record and key to the memory cache and returns true.

Cached db file data lives in exodus process memory and is lost when the process terminates or clearcache() is called.
var record;
let file = "xo_clients", key = "XD001";
if (record.readc(file, key)) ... ok
// or
if (readc(record from file, key)) ... ok

// Verify not in actual database file by using read() not readc()
if (read(record from file, key)) abort("Error: " ^ key ^ " should not be in the actual database file"); // error
ifdbfile.deletec(key)

Deletes a record and key from a memory cached "file".

The actual database file is NOT updated.

Returns: False if the key doesnt exist
var file = "xo_clients", key = "XD001";
if (file.deletec(key)) ... ok
// or
if (deletec(file, key)) ...
conn.clearcache()

Clears the memory cache of all records for the given connection

All future cache readc() function calls will be forced to obtain records from the actual database and refresh the cache.
conn.clearcache();
// or
clearcache(conn);
var=strvar.xlate(filename, fieldno, mode)

The xlate ("translate") function is similar to readf() but, when called as an exodus program member function, it can be used efficiently with exodus file dictionaries using column names and functions and multivalued data.

Arguments:

strvar: Used as the primary key to lookup a field in a given file and field no or field name.

filename: The db file in which to look up data.

If var key is multivalued then a multivalued field is returned.

fieldno: Determines which field of the record is returned.

* Integer returns that field number

* 0 means return the key unchanged.

* "" means return the whole record.

mode: Determines what is returned if the record does not exist for the given key and file.

* "X" returns ""

* "C" returns the key unconverted.
let key = "SB001";
let client_name = key.xlate("xo_clients", 1, "X"); // "Client AAA"
// or
let name_and_type = xlate("xo_clients", key, "NAME_AND_TYPE", "X"); // "Client AAA (A)"
Database Sort/Select
Use Function Description
ifdbfile.select(sort_select_command = "")

Create an active select list of keys of a database file.

The select(command) function searches and orders database records for subsequent processing given an English language-like command.

The primary job of a database, beyond mere storage and retrieval of information, is to allow rapid searching and ordering of information on demand.

In Exodus, searching and ordering of information is known as "sort/select" and is performed by the select() function.

Executing the select() function creates an "active select list" which can then be consumed by the readnext() function.

dbfile: A opened database file or file name, or an open connection or an empty var for default connections. Subsequent readnext calls must use the same.

sort_select_command: A natural language command using dictionary field names. The command can be blank if a dbfile or filename is given in dbfile or just a file name and all keys will be selected in undefined order.

Example: "select xo_clients with type 'B' and with balance ge 100 by type by name"

Option: "(R)" appended to the sort_select_command acquires the database records as well.

Returns: True if any records are selected or false if none.

Throws: VarDBException in case of any syntax error in the command.

Active select lists created using var.select()'s member function syntax cannot be consumed by the free function form of readnext() and vice versa.
var clients = "xo_clients";
if (clients.select("with type 'B' and with balance ge 100 by type by name"))
    while (clients.readnext(ID))
        println("Client code is {}", ID);
// or
if (select("xo_clients with type 'B' and with balance ge 100 by type by name"))
    while (readnext(ID))
        println("Client code is {}", ID);
ifdbfile.selectkeys(keys)

Create an active select list from a string of keys.

Similar to select() but creates the list directly from a var.

keys: An FM separated list of keys or key^VM^valueno pairs.

Returns: True if any keys are provided or false if not.
var dbfile = "";
let keys = "A01^B02^C03"_var;
if (dbfile.selectkeys(keys)) ... ok
assert(dbfile.readnext(ID) and ID == "A01");
// or
if (selectkeys(keys)) ... ok
assert(readnext(ID) and ID == "A01");
ifdbfile.hasnext()

Checks if a select list is active.

dbfile: A file or connection var used in a prior select, selectkeys or getlist function call.

Returns: True if a select list is active and false if not.

If it returns true then a call to readnext() will return a database record key, otherwise not.
var clients = "xo_clients", key;
if (clients.select()) {
    assert(clients.hasnext());
}
// or
if (select("xo_clients")) {
    assert(hasnext());
}
ifdbfile.readnext(out key)

Acquires and consumes one key from an active select list of database record keys.

dbfile: A file or connection var used in a prior select, selectkeys or getlist function call.

key: Returns the first (next) key present in an active select list or "" if no select list is active.

Returns: True if a list is active and a key is available, false if not.

Each call to readnext consumes one key from the list.

Once all the keys in an active select list have been consumed by calls to readnext, the list becomes inactive.

See select() for example code.

ifdbfile.readnext(out key, out valueno)

Similar to readnext(key) but multivalued.

If the active list was ordered by multivalued database fields then pairs of key and multivalue number will be available to the readnext function.

ifdbfile.readnext(out record, out key, out valueno)

Similar to readnext(key) but acquires the database record as well.

record: Returns the next database record from the select list assuming that the select list was created with the (R) option otherwise "" if not.

key: Returns the next database record key in the select list.

valueno: The multivalue number if the select list was ordered on multivalued database record fields or 1 if not.
var clients = "xo_clients";
if (clients.select("with type 'B' and with balance ge 100 by type by name (R)"))
    while (clients.readnext(RECORD, ID, MV))
        println("Code is {}, Name is {}", ID, RECORD.f(1));
// or
DICT = "dict.xo_clients";
if (select("xo_clients with type 'B' and with balance ge 100 by type by name (R)"))
    while (readnext(RECORD, ID, MV))
        println("Code is {}, Name is {}", calculate("CODE"), calculate("NAME"));
dbfile.clearselect()

Deactivates an active select list.

dbfile: A file or connection var used in a prior select, selectkeys or getlist function call.

Returns: Nothing

Has no effect if no select list is active for dbfile.
var clients = "xo_clients";
clients.clearselect();
if (not clients.hasnext()) ... ok
// or
clearselect();
if (not hasnext()) ... ok
ifdbfile.savelist(listname)

Stores an active select list for later retrieval.

dbfile: A file or connection var used in a prior select, selectkeys or getlist function call.

listname: A suitable name that will be required for later retrieval.

Returns: True if saved successfully or false if there was no active list to be saved.

Any existing list with the same name will be overwritten.

Only the remaining unconsumed part of the active select list is saved.

Saved lists are stand-alone and are not tied to specific database files although they usually hold keys related to specific files.

Saved lists can be created from one file and used to access another.

savelist() merely writes an FM separated string of keys as a record in the "lists" database file using the list name as the key of the record.

If a saved list is very long, additional blocks of keys for the same list may be stored with keys like listname*2, listname*3 etc.

Select lists saved in the lists database file may be created, deleted and listed like database records in any other database file.
var clients = "xo_clients";
if (clients.select("with type 'B' by name")) {
}
// or
if (select("xo_clients with type 'B' by name")) {
    if (savelist("mylist")) ... ok
}
ifdbfile.getlist(listname)

Retrieve and reactivate a saved select list.

dbfile: A file or connection var to be used by subsequent readnext function calls.

listname: The name of an existing list in the "lists" database file, either created by savelist or manually.

Returns: True if the list was successfully retrieved and activated, or false if the list name doesnt exist.

Any currently active select list is replaced.

Retrieving a list does not delete it and a list can be retrieved more than once until specifically deleted.
var file = "";
if (file.getlist("mylist")) {
    while (file.readnext(ID))
        println("Key is {}", ID);
}
// or
if (getlist("mylist")) {
    while (readnext(ID))
        println("Key is {}", ID);
}
ifdbfile.deletelist(listname)

Delete a saved select list.

dbfile: A file or connection to the desired database.

listname: The name of an existing list in the "lists" database file.

Returns: True if successful or false if the list name doesnt exist.
var conn = "";
if (conn.deletelist("mylist")) ... ok
// or
if (deletelist("mylist")) ...
OS Time/Date
Use Function Description
var=var::date()

Number of whole days since pick epoch 1967-12-31 00:00:00 UTC. Negative for dates before.

e.g. was 20821 from 2025-01-01 00:00:00 UTC for 24 hours
let today1 = var::date();
// or
let today2 = date();
var=var::time()

Number of whole seconds since last 00:00:00 (UTC).

e.g. 43200 if time is 12:00

Range 0 - 86399 since there are 24*60*60 (86400) seconds in a day.
let now1 = var::time();
// or
let now2 = time();
var=var::ostime()

Number of fractional seconds since last 00:00:00 (UTC).

A floating point with approx. nanosecond resolution depending on hardware.

e.g. 23343.704387955 approx. 06:29:03 UTC
let now1 = var::ostime();
// or
let now2 = ostime();
var=var::ostimestamp()

Number of fractional days since pick epoch 1967-12-31 00:00:00 UTC. Negative for dates before.

A floating point with approx. nanosecond resolution depending on hardware.

e.g. Was 20821.99998842593 around 2025-01-01 23:59:59 UTC
let now1 = var::ostimestamp();
// or
let now2 = ostimestamp();
var=vardate.ostimestamp(ostime)Construct a timestamp from a date and time
let idate = iconv("2025-01-01", "D"), itime = iconv("23:59:59", "MT");
let ts1 = idate.ostimestamp(itime); // 20821.99998842593
// or
let ts2 = ostimestamp(idate, itime);
var::ossleep(milliseconds)

Sleep/pause/wait for a number of milliseconds

Releases the processor if not needed for a period of time or a delay is required.
var::ossleep(100); // sleep for 100ms
// or
ossleep(100);
var=file_dir_list.oswait(milliseconds)

Sleep/pause/wait up to a given number of milliseconds or until any changes occur in an FM delimited list of directories and/or files.

Any terminal input (e.g. a key press) will also terminate the wait.

An FM array of event information is returned. See below.

Multiple events are returned in multivalues.

let v1 = ".^/etc/hosts"_var.oswait(100); /// e.g. "IN_CLOSE_WRITE^/etc^hosts^f"_var
// or
let v2 = oswait(".^/etc/hosts"_var, 100);
Returned array fields

1. Event type codes

2. dirpaths

3. filenames

4. d=dir, f=file

Possible event type codes are as follows:

* IN_CLOSE_WRITE - A file opened for writing was closed

* IN_ACCESS - Data was read from file

* IN_MODIFY - Data was written to file

* IN_ATTRIB - File attributes changed

* IN_CLOSE - File was closed (read or write)

* IN_MOVED_FROM - File was moved away from watched directory

* IN_MOVED_TO - File was moved into watched directory

* IN_MOVE - File was moved (in or out of directory)

* IN_CREATE - A file was created in the directory

* IN_DELETE - A file was deleted from the directory

* IN_DELETE_SELF - Directory or file under observation was deleted

* IN_MOVE_SELF - Directory or file under observation was moved

OS File I/O
Use Function Description
ifosfilevar.osopen(osfilename, utf8 = true)

Initialises an os file handle var that can be used for random read and write

osfilename: The name of an existing os file name including path.

utf8: Defaults to true which causes trimming of partial UTF-8 Unicode byte sequences from the end of osbreads. For raw untrimmed osbreads pass tf8 = false;

osfilevar: [out] To be used in subsequent calls to osbread() and osbwrite()

Returns: True if successful or false if not possible for any reason. e.g. Target doesnt exist, permissions etc.

The file will be opened for writing if possible otherwise for reading.
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
if (oswrite("" on osfilename)) ... ok /// Create an empty os file
var ostempfile;
if (ostempfile.osopen(osfilename)) ... ok
// or
if (osopen(osfilename to ostempfile)) ... ok
ifosfilevar.osbwrite(osfilevar, io offset)

Writes data to an existing os file starting at a given byte offset (0 based).

See osbread for more info.
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
let text = "aaa=123\nbbb=456\n";
var offset = osfile(osfilename).f(1); /// Size of file therefore append
if (text.osbwrite(osfilename, offset)) ... ok // offset -> 16
// or
if (not osbwrite(text on osfilename, offset)) ...
ifosfilevar.osbread(osfilevar, io offset, length)

Reads length bytes from an existing os file starting at a given byte offset (0 based).

The osfilevar file handle may either be initialised by osopen or be just be a normal string variable holding the path and name of the os file.

After reading, the offset is updated to point to the correct offset for a subsequent sequential read.

If reading UTF8 data (the default) then the length of data actually returned may be a few bytes shorter than requested in order to be a complete number of UTF-8 code points.
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
var text, offset = 0;
if (text.osbread(osfilename, offset, 8)) ... ok // text -> "aaa=123\n" // offset -> 8
// or
if (osbread(text from osfilename, offset, 8)) ... ok // text -> "bbb=456\n" // offset -> 16
osfilevar.osclose()

Removes an osfilevar handle from the internal memory cache of os file handles. This frees up both exodus process memory and operating system resources.

It is advisable to osclose any file handles after use, regardless of whether they were specifically opened using osopen or not, especially in long running programs. Exodus performs caching of internal os file handles per thread and os file. If not closed, then the operating system will probably not flush deleted files from storage until the process is terminated. This can potentially create an memory issue or file system resource issue especially if osopening/osreading/oswriting many perhaps temporary files in a long running process.
osfilevar.osclose();
// or
osclose(osfilevar);
ifstrvar.oswrite(osfilename, codepage = "")

Create a complete os file from a var.

strvar: The text or data to be used to create the file.

osfilename: Absolute or relative path and filename to be written. Any existing os file is removed first.

codepage: If specified then output is converted from UTF-8 to that codepage before being written. Otherwise no conversion is done.

Returns: True if successful or false if not possible for any reason. e.g. Path is not writeable, permissions etc.
let text = "aaa = 123\nbbb = 456";
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
if (text.oswrite(osfilename)) ... ok
// or
if (oswrite(text on osfilename)) ... ok
ifstrvar.osread(osfilename, codepage = "")

Read a complete os file into a var.

osfilename: Absolute or relative path and filename to be read.

codepage: If specified then input is converted from that codepage to UTF-8 after being read. Otherwise no conversion is done.

strvar: [out] is currently set to "" in case of any failure but this is may be changed in a future release to either force var to be unassigned or to leave it untouched. To guarantee future behaviour either add a line 'xxxx.defaulter("")' or set var manually in case osread() returns false. Or use the one argument free function version of osread() which always returns "" in case of failure to read.

Returns: True if successful or false if not possible for any reason. e.g. File doesnt exist, insufficient permissions etc.
var text;
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
if (text.osread(osfilename)) ... ok // text -> "aaa = 123\nbbb = 456"
// or
if (osread(text from osfilename)) ... ok
let text2 = osread(osfilename);
ifosfile_or_dirname.osrename(new_dirpath_or_filepath)

Renames an os file or dir in the OS file system.

The source and target must exist in the same storage device.

osfile_or_dirname: Absolute or relative path and file or dir name to be renamed.

new_dirpath_or_filepath: Will not overwrite an existing os file or dir.

Returns: True if successful or false if not possible for any reason. e.g. Target already exists, path is not writeable, permissions etc.

Uses std::filesystem::rename internally.
let from_osfilename = ostempdir() ^ "xo_gendoc_test.conf";
let to_osfilename = from_osfilename ^ ".bak";
if (not osremove(ostempdir() ^ "xo_gendoc_test.conf.bak")) {}; // Cleanup first

if (from_osfilename.osrename(to_osfilename)) ... ok
// or
if (osrename(from_osfilename, to_osfilename)) ...
ifosfile_or_dirname.osmove(to_osfilename)

"Moves" an os file or dir within the os file system.

Attempts osrename first, then oscopy followed by osremove original.

osfile_or_dirname: Absolute or relative path and file or dir name to be moved.

to_osfilename: Will not overwrite an existing os file or dir.

Returns: True if successful or false if not possible for any reason. e.g. Source doesnt exist or cannot be accessed, target already exists, source or target is not writeable, permissions, storage space etc.
let from_osfilename = ostempdir() ^ "xo_gendoc_test.conf.bak";
let to_osfilename = from_osfilename.cut(-4);

if (not osremove(ostempdir() ^ "xo_gendoc_test.conf")) {}; // Cleanup first
if (from_osfilename.osmove(to_osfilename)) ... ok
// or
if (osmove(from_osfilename, to_osfilename)) ...
ifosfile_or_dirname.oscopy(to_osfilename)

Copies an os file or directory recursively within the os file system.

osfile_or_dirname: Absolute or relative path and file or dir name to be copied.

to_osfilename: Will overwrite an existing os file or merge into an existing dir.

Returns: True if successful or false if not possible for any reason. e.g. Source doesnt exist or cannot be accessed, target is not writeable, permissions, storage space, etc.

Uses std::filesystem::copy internally with recursive and overwrite options
let from_osfilename = ostempdir() ^ "xo_gendoc_test.conf";
let to_osfilename = from_osfilename ^ ".bak";

if (from_osfilename.oscopy(to_osfilename)) ... ok;
// or
if (oscopy(from_osfilename, to_osfilename)) ... ok
ifosfilename.osremove()

Removes/deletes an os file from the OS file system.

Will not remove directories. Use osrmdir() to remove directories

osfilename: Absolute or relative path and file name to be removed.

Returns: True if successful or false if not possible for any reason. e.g. Target doesnt exist, path is not writeable, permissions etc.
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
if (osfilename.osremove()) ... ok
// or
if (osremove(osfilename)) ...
OS Directories
Use Function Description
var=dirpath.oslist(globpattern = "", mode = 0)

Get a list of os files and/or dirs.

dirpath: Absolute or relative dir path.

globpattern: e.g. *.conf to be appended to the dirpath or a complete path plus glob pattern e.g. /etc/ *.conf.

mode: 0: default - Any regular files or dirs. 1 - Only regular os files. 2 - Only dirs.

Returns: An FM delimited string containing all matching dir entries given a dir path
var entries1 = "/etc/"_var.oslist("*.cfg"); /// e.g. "adduser.conf^ca-certificates.con^... etc."
// or
var entries2 = oslist("/etc/" "*.conf");
var=dirpath.oslistf(globpattern = "")Same as oslist for files only
var=dirpath.oslistd(globpattern = "")Same as oslist for files only
var=osfile_or_dirpath.osinfo(mode = 0)

Get dir info about an os file or dir.

Returns: A short string containing size ^ FM ^ modified_time ^ FM ^ modified_time or "" if not a regular file or dir.

mode: 0: default. 1: Must be a regular os file. 2: Must be an os dir.

See also osfile() and osdir()
var info1 = "/etc/hosts"_var.osinfo(); /// e.g. "221^20597^78309"_var
// or
var info2 = osinfo("/etc/hosts");
var=osfilename.osfile()

Get dir info of an os file.

osfilename: Absolute or relative path and file name.

Returns: A short string containing size ^ FM ^ modified_time ^ FM ^ modified_time or "" if not a regular file.

Alias for osinfo(1)
var fileinfo1 = "/etc/hosts"_var.osfile(); /// e.g. "221^20597^78309"_var
// or
var fileinfo2 = osfile("/etc/hosts");
var=dirpath.osdir()

Get dir info of an os dir.

dirpath: Absolute or relative path and dir name.

Returns: A short string containing FM ^ modified_time ^ FM ^ modified_time or "" if not a dir.

Alias for osinfo(2)
var dirinfo1 = "/etc/"_var.osdir(); /// e.g. "^20848^44464"_var
// or
var dirinfo2 = osfile("/etc/");
ifdirpath.osmkdir()

Create a new os file system directory.

Parent dirs wil be created if necessary.

dirpath: Absolute or relative path and dir name.

Returns: True if successful.
let osdirname = "xo_test/aaa";
if (osrmdir("xo_test/aaa")) {}; // Cleanup first
if (osdirname.osmkdir()) ... ok
// or
if (osmkdir(osdirname)) ...
ifvar::oscwd(newpath)

Changes the current working dir.

newpath: An absolute or relative dir path and name.

Returns: True if successful or false if not. e.g. Invalid dirpath, insufficient permission etc.
let osdirname = "xo_test/aaa";
if (osdirname.oscwd()) ... ok
// or
if (oscwd(osdirname)) ... ok
if (oscwd("../..")) ... ok /// Change back to avoid errors in following code.
var=var::oscwd()

Gets the current dir path and name.

Returns: The current working dir path and name.

e.g. "/root/exodus/cli/src/xo_test/aaa"
var cwd1 = var().oscwd();
// or
var cwd2 = oscwd();
ifdirpath.osrmdir(evenifnotempty = false)

Removes (deletes) an os dir,

eventifnotempty: If true any subdirs will also be removed/deleted recursively, otherwise the function will fail and return false.

Returns: Returns true if successful or false if not. e.g dir doesnt exist, insufficient permission, not empty etc.
let osdirname = "xo_test/aaa";
if (osdirname.osrmdir()) ... ok
// or
if (osrmdir(osdirname)) ...
OS Shell/Environment
Use Function Description
ifcommand.osshell()

Execute a shell command.

command: An executable command to be interpreted by the default os shell.

Returns: True if the process terminates with error status 0 and false otherwise.

Append "&>/dev/null" to the command to suppress terminal output.
let cmd = "echo $HOME";
if (cmd.osshell()) ... ok
// or
if (osshell(cmd)) ... ok
ifinstr.osshellread(oscmd)

Same as osshell but captures and returns stdout

Returns: The stout of the shell command.

Append "2>&1" to the command to capture stderr/stdlog output as well.
let cmd = "echo $HOME";
var text;
if (text.osshellread(cmd)) ... ok

// or capturing stdout but ignoring exit status
text = osshellread(cmd);
ifoutstr.osshellwrite(oscmd)

Same as osshell but provides stdin to the process

Returns: True if the process terminates with error status 0 and false otherwise.

Append "&> somefile" to the command to suppress and/or capture output.
let outtext = "abc xyz";
if (outtext.osshellwrite("grep xyz")) ... ok
// or
if (osshellwrite(outtext, "grep xyz")) ... ok
var=var::ostempdir()

Get the tmp dir path and name.

Returns: A string e.g. "/tmp/"
let v1 = var::ostempdir();
// or
let v2 = ostempdir();
var=var::ostempfile()

Create a temporary file

Returns: The name of new temporary file e.g. "/tmp/~exoEcLj3C"
var temposfilename1 = var::ostempfile();
// or
var temposfilename2 = ostempfile();
envvalue.ossetenv(envcode)

Set the value of an environment variable

envcode: The code of the env variable to set.

envvalue: The new value to set the env code to.
let envcode = "EXO_ABC", envvalue = "XYZ";
envvalue.ossetenv(envcode);
// or
ossetenv(envcode, envvalue);
ifenvvalue.osgetenv(envcode)

Get the value of an environment variable.

envcode: The code of the env variable to get or "" for all.

envvalue: [out] Set to the value of the env variable if set otherwise "". If envcode is "" then envvalue is set to a dynamic array of all environment variables LIKE CODE1=VALUE1^CODE2=VALUE2...

Returns: True if the envcode is set or false if not.

osgetenv and ossetenv work with a per thread copy of the os process environment. This avoids multithreading issues but does not change the process environment. Child processes created by var::osshell() will not inherit any env variables set using ossetenv() so the oscommand will need to be prefixed to achieve the desired result.

For the actual system environment, see "man environ". extern char **environ; // environ is a pointer to an array of pointers to char* env pairs like xxx=yyy and the last pointer in the array is nullptr.
var envvalue1;
if (envvalue1.osgetenv("HOME")) ... ok // e.g. "/home/exodus"
// or
let envvalue2 = osgetenv("EXO_ABC"); // "XYZ"
var=var::ospid()

Get the current os process id

Returns: A number e.g. 663237.
let pid1 = var::ospid(); /// e.g. 663237
// or
let pid2 = ospid();
var=var::ostid()

Get the current os thread process id

Returns: A number e.g. 663237.
let tid1 = var::ostid(); /// e.g. 663237
// or
let tid2 = ostid();
var=var::version()

Get the exodus library version info.

Returns: The git commit details as at the time the library was built.
// e.g.
// Local:  doc 2025-03-19 18:15:31 +0000 219cdad8a
// Remote: doc 2025-03-17 15:03:00 +0000 958f412f0
// https://github.com/exodusdb/exodusdb/commit/219cdad8a
// https://github.com/exodusdb/exodusdb/archive/958f412f0.tar.gz
//
let v1 = var::version();
// or
let v2 = version();
ifstrvar.setxlocale(newlocalecode)

Sets the current thread's default locale.

strvar: The new locale codepage code.

True if successful
if (var::setxlocale("en_US.utf8")) ... ok
// or
if (setxlocale("en_US.utf8")) ... ok
var=var.getxlocale()

Gets the current thread's default locale.

Returns: A locale codepage code string.
let v1 = var::getxlocale(); // "en_US.utf8"
// or
let v2 = getxlocale();
Output
Use Function Description
exprvarstr.outputl(prefix = "")

Output to stdout with optional prefix.

Appends an NL char.

Is FLUSHED, not buffered.

The raw string bytes are output. No character or byte conversion is performed.
"abc"_var.outputl("xyz = "); /// Sends "xyz = abc\n" to stdout and flushes.
// or
outputl("xyz = ", "abc"); /// Any number of arguments is allowed. All will be output.
exprvarstr.output(prefix = "") Same as outputl() but doesnt append an NL char and is BUFFERED, not flushed.
exprvarstr.outputt(prefix = "") Same as outputl() but appends a tab char instead of an NL char and is BUFFERED, not flushed.
exprvarstr.logputl(prefix = "")

Output to stdlog with optional prefix.

Appends an NL char.

Is BUFFERED not flushed.

Any of the six types of field mark chars present are converted to their visible versions,
"abc"_var.logputl("xyz = "); /// Sends "xyz = abc\n" to stdlog buffer and is not flushed.
// or
logputl("xyz = ", "abc");; /// Any number of arguments is allowed. All will be output.
exprvarstr.logput(prefix = "") Same as logputl() but doesnt append an NL char.
exprvarstr.errputl(prefix = "")

Output to stderr with optional prefix.

Appends an NL char.

Is FLUSHED not buffered.

Any of the six types of field mark chars present are converted to their visible versions,
"abc"_var.errputl("xyz = "); /// Sends "xyz = abc\n" to stderr
// or
errputl("xyz = ", "abc"); /// Any number of arguments is allowed. All will be output.
exprvarstr.errput(prefix = "") Same as errputl() but doesnt append an NL char and is BUFFERED not flushed.
exprvarstr.put(std::ostream& ostream1)

Output to a given stream.

Is BUFFERED not flushed.

The raw string bytes are output. No character or byte conversion is performed.

var().osflush()Flush any and all buffered output to stdout and stdlog.
var().osflush();
// or
osflush();
Input
Use Function Description
ifvar.input(prompt = "")

Returns one line of input from stdin.

Returns: True if successful or false if EOF or user pressed Esc or Ctrl+X in a terminal.

var: [in] The default value for terminal input and editing. Ignored if not a terminal.

var: [out] Raw bytes up to but excluding the first new line char. In case of EOF or user pressed Esc or Ctrl+X in a terminal it will be changed to "".

Prompt: If provided, it will be displayed on the terminal.

Multibyte/UTF8 friendly.
// var v1 = "defaultvalue";
// if (v1.input("Prompt:")) ... ok
// or
// var v2 = input();
exprvar.inputn(nchars)

Get raw bytes from standard input.

Any new line chars are treated like any other bytes.

Care must be taken to handle incomplete UTF8 byte sequences at the end of one block and the beginning of the next block.

Returns: The requested number of bytes or fewer if not available.

nchars:

99 : Get up to 99 bytes or fewer if not available. Caution required with UTF8.

⋅0 : Get all bytes presently available.

⋅1 : Same as keypressed(true). Deprecated.

-1 : Same as keypressed(). Deprecated.

exprvar.keypressed(wait = false)

Return the code of the current terminal key pressed.

wait: Defaults to false. True means wait for a key to be pressed if not already pressed.

Returns: ASCII or key code defined according to terminal protocol.

Returns: "" if stdin is not a terminal.

e.g. The PgDn key if pressed might return an escape sequence like "\x1b[6~"

It only takes a few µsecs to return false if no key is pressed.
var v1; v1.keypressed();
// or
var v2 = keypressed();
ifvar().isterminal(arg = 1)

Checks if one of stdin, stdout, stderr is a terminal or a file/pipe.

arg: 0 - stdin, 1 - stdout (Default), 2 - stderr.

Returns: True if it is a terminal or false if it is a file or pipe.

Note that if the process is at the start or end of a pipeline, then only stdin or stdout will be a terminal.

The type of stdout terminal can be obtained from the TERM environment variable.
var v1 = var().isterminal(); /// 1 or 0
// or
var v2 = isterminal();
ifvar().hasinput(milliseconds = 0)

Checks if stdin has any bytes available for input.

If no bytes are immediately available, the process sleeps for up to the given number of milliseconds, returning true immediately any bytes become available or false if the period expires without any bytes becoming available.

Returns: True if any bytes are available otherwise false.

It only takes a few µsecs to return false if no bytes are available and no wait time has been requested.

ifvar().eof()

True if stdin is at end of file

ifvar().echo(on_off = true)

Sets terminal echo on or off.

"On" causes all stdin data to be reflected to stdout if stdin is a terminal.

Turning terminal echo off can be used to prevent display of confidential information.

Returns: True if successful.

var().breakon()

Install various interrupt handlers.

Automatically called in program/thread initialisation by exodus_main.

SIGINT - Ctrl+C -> "Interrupted. (C)ontinue (Q)uit (B)acktrace (D)ebug (A)bort ?"

SIGHUP - Sets a variable "RELOAD_req" which may be handled or ignored by the program.

SIGTERM - Sets a variable "TERMINATE_req" which may be handled or ignored by the program.

var().breakoff()

Disable keyboard interrupt.

Ctrl+C becomes inactive in terminal.

Math/Boolean
Use Function Description
var=varnum.abs()Absolute value
let v1 = -12.34;
let v2 = v1.abs(); // 12.34
// or
let v3 = abs(v1);
var=varnum.pwr(exponent)Power
let v1 = var(2).pwr(8); // 256
// or
let v2 = pwr(2, 8);
varnum.initrnd()

Initialise the seed for rnd()

Allows the stream of pseudo random numbers generated by rnd() to be reproduced.

Seeded from std::chrono::high_resolution_clock::now() if the argument is 0;
var(123).initrnd(); /// Set seed to 123
// or
initrnd(123);
var=varnum.rnd()

Pseudo random number generator

Returns: a pseudo random integer between 0 and the provided maximum minus 1.

Uses std::mt19937 and std::uniform_int_distribution
let v1 = var(100).rnd(); /// Random 0 to 99
// or
let v2 = rnd(100);
var=varnum.exp()Power of e
let v1 = var(1).exp(); // 2.718281828459045
// or
let v2 = exp(1);
var=varnum.sqrt()Square root
let v1 = var(100).sqrt(); // 10
// or
let v2 = sqrt(100);
var=varnum.sin()Sine of degrees
let v1 = var(30).sin(); // 0.5
// or
let v2 = sin(30);
var=varnum.cos()Cosine of degrees
let v1 = var(60).cos(); // 0.5
// or
let v2 = cos(60);
var=varnum.tan()Tangent of degrees
let v1 = var(45).tan(); // 1
// or
let v2 = tan(45);
var=varnum.atan()Arctangent of degrees
let v1 = var(1).atan(); // 45
// or
let v2 = atan(1);
var=varnum.loge()

Natural logarithm

Returns: Floating point ver (double)
let v1 = var(2.718281828459045).loge(); // 1
// or
let v2 = loge(2.718281828459045);
var=varnum.integer()

Truncate decimal numbers towards zero

Returns: An integer var
let v1 = var(2.9).integer(); // 2
// or
let v2 = integer(2.9);

var v3 = var(-2.9).integer(); // -2
// or
var v4 = integer(-2.9);
var=varnum.floor()

Truncate decimal numbers towards negative

Returns: An integer var
let v1 = var(2.9).floor(); // 2
// or
let v2 = floor(2.9);

var v3 = var(-2.9).floor(); // -3
// or
var v4 = floor(-2.9);
var=varnum.mod(modulus)

Modulus function

Identical to C++ % operator only for positive numbers and modulus

Negative denominators are considered as periodic with positiive numbers

Result is between [0, modulus) if modulus is positive

Result is between (modulus, 0] if modulus is negative (symmetric)

Throws: VarDivideByZero if modulus is zero.

Floating point works.
let v1 = var(11).mod(5); // 1
// or
let v2 = mod(11, 5); // 1
let v3 = mod(-11, 5); // 4
let v4 = mod(11, -5); // -4
let v5 = mod(-11, -5); // -1
int=var::setprecision(newprecision)

Set the maximum floating point precision.

This is the number of post-decimal point digits to consider for floating point comparison and implicit conversion to strings.

The default precision is 4 which is 0.0001.

NUMBERS AND DIFFERENCES SMALLER THAN 0.0001 ARE TREATED AS ZERO UNLESS PRECISION IS INCREASED.

newprecision: New precision between -307 and 308 inclusive.

Returns: The new precision if successful or the old precision if not.

Not required if using common numbers or using the explicit rounding and formatting functions to convert numbers to strings.

Increasing the precision allows comparing and outputting smaller numbers but creates errors handling large numbers.

Setting precision inside a perform, execute or dictionary function lasts until termination of the function.

See cli/demo_precision for more info.
assert(0.000001_var == 0); /// NOTE WELL: Default precision 4.
let new_precision1 = var::setprecision(6); // 6 // Increase the precision.
// or
let new_precision2 = setprecision(6);
assert(0.000001_var != 0); /// NOTE: Precision 6.
int=var::getprecision()

Returns: The current precision setting.

See setprecision() for more info.
let curr_precision1 = var::getprecision();
// or
let curr_precision2 = getprecision();

I/O Conversion Codes

Use Function Description
var=vardate.oconv("D")

Date output: Convert internal date format to human readable date or calendar info in text format.

Returns: Human readable date or calendar info, or the original value unconverted if non-numeric.

Flags: See examples below.

Any Dynamic array structure is preserved.
let v1 = 19002;
var v2;
v2 =  v1.oconv( "D"   ) ; //  "09 JAN 2020"   // Default

v2 =  v1.oconv( "D/"  ) ; //  "01/09/2020"    // mm/dd/yyyy - American numeric
v2 =  v1.oconv( "D-"  ) ; //  "01-09-2020"    // mm-dd-yyyy - American numeric

v2 =  v1.oconv( "D/E" ) ; //  "09/01/2020"    // dd/mm/yyyy - International numeric
v2 =  v1.oconv( "D-E" ) ; //  "09-01-2020"    // dd-mm-yyyy - International numeric

v2 =  v1.oconv( "D2"  ) ; //  "09 JAN 20"     // 2 digit year
v2 =  v1.oconv( "D0"  ) ; //  "09 JAN"        // No year

v2 =  v1.oconv( "DS"  ) ; //  "2020 JAN 09"   // yyyy mmm dd - ISO year first, alpha month
v2 =  v1.oconv( "DS-" ) ; //  "2020-01-09"    // yyyy-mm-dd  - ISO year first, numeric month

v2 =  v1.oconv( "DZ"  ) ; //  " 9 JAN 2020"   // Leading 0 become spaces
v2 =  v1.oconv( "DZZ" ) ; //  "9 JAN 2020"    // Leading 0 are suppressed
v2 =  v1.oconv( "D!"  ) ; //  "09JAN2020"     // No separators
v2 =  v1.oconv( "DS-!") ; //  "20200109"      // yyyymmdd packed

v2 =  v1.oconv( "DM"  ) ; //  "1"             // Month number
v2 =  v1.oconv( "DMA" ) ; //  "JANUARY"       // Month name
v2 =  v1.oconv( "DY"  ) ; //  "2020"          // Year number
v2 =  v1.oconv( "DY2" ) ; //  "20"            // Year 2 digits
v2 =  v1.oconv( "DD"  ) ; //  "9"             // Day number in month (1-31)
v2 =  v1.oconv( "DW"  ) ; //  "4"             // Weekday number (1-7)
v2 =  v1.oconv( "DWA" ) ; //  "THURSDAY"      // Weekday name
v2 =  v1.oconv( "DQ"  ) ; //  "1"             // Quarter number
v2 =  v1.oconv( "DJ"  ) ; //  "9"             // Day number in year
v2 =  v1.oconv( "DL"  ) ; //  "31"            // Last day number of month (28-31)

// Dynamic array
let v3 = "12345^12346]12347"_var;
v2 = v3.oconv("D") ; //  "18 OCT 2001^19 OCT 2001]20 OCT 2001"_var

 // or
 v2 =  oconv(v3, "D"   ) ;
var=varstr.iconv("D")

Date input: Convert human readable date to internal date format.

Returns: Internal date or "" if the input is an invalid date.

Internal date format is whole days since 1967-12-31 00:00:00 which is day 0.

Any Dynamic array structure is preserved.
// International order "DE"
var v2;
v2 =             oconv(19005, "DE") ; //  "12 JAN 2020"
v2 =    "12/1/2020"_var.iconv("DE") ; //  19005
v2 =    "12 1 2020"_var.iconv("DE") ; //  19005
v2 =    "12-1-2020"_var.iconv("DE") ; //  19005
v2 =  "12 JAN 2020"_var.iconv("DE") ; //  19005
v2 =  "jan 12 2020"_var.iconv("DE") ; //  19005

// American order "D"
v2 =             oconv(19329, "D") ; //  "01 DEC 2020"
v2 =    "12/1/2020"_var.iconv("D") ; //  19329
v2 =   "DEC 1 2020"_var.iconv("D") ; //  19329
v2 =   "1 dec 2020"_var.iconv("D") ; //  19329

// Reverse order
v2 =   "2020/12/1"_var.iconv("DE") ; //  19329
v2 =    "2020-12-1"_var.iconv("D") ; //  19329
v2 =   "2020 1 dec"_var.iconv("D") ; //  19329

//Invalid date
v2 =    "2/29/2021"_var.iconv("D") ; //  ""
v2 =   "29/2/2021"_var.iconv("DE") ; //  ""

// or
v2 = iconv("12/1/2020"_var, "DE") ; //  19005
var=vartime.oconv("MT")

Time output: Convert internal time format to human readable time e.g. "10:30:59".

Returns: Human readable time or the original value unconverted if non-numeric.

Conversion code (e.g. "MTHS") is "MT" + flags ...

Flags:

"H" - Show AM/PM otherwise 24 hour clock is used.

"S" - Output seconds

"2" = Ignored (used in iconv)

":" - Any other flag is used as the separator char instead of ":"

Any Dynamic array structure is preserved.
let v1  = 62000;
var v2;
v2 = v1.oconv("MT"  ); // "17:13"      // Default
v2 = v1.oconv("MTH" ); // "05:13PM"    // 'H' flag for AM/PM
v2 = v1.oconv("MTS" ); // "17:13:20"   // 'S' flag for seconds
v2 = v1.oconv("MTHS"); // "05:13:20PM" // Both flags

let v3  = 0;
v2 = v3.oconv("MT"  ); // "00:00"
v2 = v3.oconv("MTH" ); // "12:00AM"
v2 = v3.oconv("MTS" ); // "00:00:00"
v2 = v3.oconv("MTHS"); // "12:00:00AM"

// Dynamic array
let v4  = "61980^62040]62100"_var;
v2 = v4.oconv("MT");    // "17:13^17:14]17:15"_var

// or
v2 = oconv(v1, "MT");    // "17:13"
var=varstr.iconv("MT")

Time input: Convert human readable time (e.g. "10:30:59") to internal time format.

Returns: Internal time or "" if the input is an invalid time.

Internal time format is whole seconds since midnight.

Accepts: Two or three groups of digits surrounded and separated by any non-digits char(s).

Any Dynamic array structure is preserved.
var v2;
v2 =       "17:13"_var.iconv( "MT" ) ; //  61980
v2 =     "05:13PM"_var.iconv( "MT" ) ; //  61980
v2 =    "17:13:20"_var.iconv( "MT" ) ; //  62000
v2 =  "05:13:20PM"_var.iconv( "MT" ) ; //  62000

v2 =       "00:00"_var.iconv( "MT" ) ; //  0
v2 =     "12:00AM"_var.iconv( "MT" ) ; //  0     // Midnight
v2 =     "12:00PM"_var.iconv( "MT" ) ; //  43200 // Noon
v2 =    "00:00:00"_var.iconv( "MT" ) ; //  0
v2 =  "12:00:00AM"_var.iconv( "MT" ) ; //  0

// Dynamic array
v2 = "17:13^05:13PM]17:13:20"_var.iconv("MT") ; //  "61980^61980]62000"_var

// or
v2 = iconv("17:13", "MT") ; //  61980
var=varnum.oconv("MD")

Number output: Convert internal numbers to external text format after rounding and optional scaling.

Returns: A string or, if the value is not numeric, then no conversion is performed and the original value is returned.

Conversion code (e.g. "MD20") is "MD" or "MC", 1st digit, 2nd digit, flags ...

MD outputs like 123.45 (International)

MC outputs like 123,45 (European)

1st digit = Decimal places to display. Also decimal places to move if 2nd digit not present and no P flag present.

2nd digit = Optional decimal places to move left if P flag not present.

Flags:

"P" - Preserve decimal places. Same as 2nd digit = 0;

"Z" - Zero flag - return "" if zero.

"X" - No conversion - return as is.

"." or "," - Separate thousands depending on MD or MC.

"-" means suffix negatives with "-" and positives with " " (space).

"<" means wrap negatives in "<" and ">" chars.

"C" means suffix negatives with "CR" and positives or zero with "DB".

"D" means suffix negatives with "DB" and positives or zero with "CR".

Any Dynamic array structure is preserved.
var v1 = -1234.567;
var v2;
v2 =  v1.oconv( "MD20"   ) ; //   "-1234.57"
v2 =  v1.oconv( "MD20,"  ) ; //  "-1,234.57"    // , flag
v2 =  v1.oconv( "MC20,"  ) ; //  "-1.234,57"    // MC code
v2 =  v1.oconv( "MD20,-" ) ; //   "1,234.57-"   // - flag
v2 =  v1.oconv( "MD20,<" ) ; //  "<1,234.57>"   // < flag
v2 =  v1.oconv( "MD20,C" ) ; //   "1,234.57CR"  // C flag
v2 =  v1.oconv( "MD20,D" ) ; //   "1,234.57DB"  // D flag

// Dynamic array
var v3 = "1.1^2.1]2.2"_var;
v2 =  v3.oconv( "MD20"   ) ; //  "1.10^2.10]2.20"_var

// or
v2 =  oconv(v1, "MD20"   ) ; //   "-1234.57"   
var=var.oconv("LRC")

Text justification: Left, right and center. Padding and truncating. See Procrustes.

e.g. "L#10", "R#10", "C#10"

Useful when outputting to terminal devices where spaces are used for alignment.

Dynamic array structure is preserved.

ASCII only.
var v2;
v2 =      "abcde"_var.oconv( "L#3" ) ; //  "abc"  // Truncating
v2 =      "abcde"_var.oconv( "R#3" ) ; //  "cde"
v2 =      "abcde"_var.oconv( "C#3" ) ; //  "abc"

v2 =      "ab"_var.oconv( "L#6" ) ; //  "ab␣␣␣␣"  // Padding
v2 =      "ab"_var.oconv( "R#6" ) ; //  "␣␣␣␣ab"
v2 =      "ab"_var.oconv( "C#6" ) ; //  "␣␣ab␣␣"

v2 =       var(42).oconv( "L(0)#5" ) ; //  "42000"  // Padding char (x)
v2 =       var(42).oconv( "R(0)#5" ) ; //  "00042"
v2 =       var(42).oconv( "C(0)#5" ) ; //  "04200"
v2 =       var(42).oconv( "C(0)#5" ) ; //  "04200"

// Dynamic array
v2 =       "f1^v1]v2"_var.oconv("L(_)#5") ; //  "f1___^v1___]v2___"_var

// Fail for non-ASCII (Should be 5)
v2 =      "🐱"_var.oconv("L#5").textwidth() ; //  3

// or
v2 =      oconv("abcd", "L#3" ) ; //  "abc" 
var=varstr.oconv("T")

Text folding and justification.

e.g. T#20

Useful when outputting to terminal devices where spaces are used for alignment.

Splits text into multiple fixed length lines by inserting spaces and TM chars.

ASCII only.
let v1 = "Have a nice day";
v2 =   v1.oconv("T#10") ; //  "Have a␣␣␣␣|nice day␣␣"_var
// or
v2 =  oconv(v1, "T#10") ; //  "Have a␣␣␣␣|nice day␣␣"_var 
exprvarnum.oconv("MR")

Character replacement

e.g. MRU
let v1 = "123/abC.";
var v2;
v2 = v1.oconv("MRL") ; //  "123/abc." // lcase
v2 = v1.oconv("MRU") ; //  "123/ABC." // ucase
v2 = v1.oconv("MRT") ; //  "123/Abc." // tcase
v2 = v1.oconv("MRN") ; //  "123"      // Return only digits
v2 = v1.oconv("MRA") ; //  "abC"      // Return only alphabetic
v2 = v1.oconv("MRB") ; //  "123abC"   // Return only alphanumeric
v2 = v1.oconv("MR/N") ; //  "/abC."   // Remove digits
v2 = v1.oconv("MR/A") ; //  "123/."   // Remove alphabetic
v2 = v1.oconv("MR/B") ; //  "/."      // Remove alphanumeric
var=varstr.oconv("HEX")

Convert the chars of a string to a string of pairs of hexadecimal digits.

varstr: A string. Numbers will be converted to strings for conversion. 1.2 -> "1.2" -> hex "312E32"

Dynamic array structure is not preserved. Field marks are converted to HEX as for all other bytes.

The size of the output is always precisely double that of the input.

This function is the exact inverse of iconv("HEX").
// var v2;
v2 =      "ab01"_var.oconv( "HEX" ) ; //  "61" "62" "30" "31"
v2 =  "\xff\x00"_var.oconv( "HEX" ) ; //  "FF" "00"            // Any bytes are ok.
v2 =         var(10).oconv( "HEX" ) ; //  "31" "30"            // Uses ASCII string equivalent of 10 i.e. "10".
v2 =    "\u0393"_var.oconv( "HEX" ) ; //  "CE" "93"            // Greek capital Gamma in UTF8 bytes.
v2 =      "a^]b"_var.oconv( "HEX" ) ; //  "61" "1E" "1D" "62"  // Field and value marks.
// or
v2 =       oconv("ab01"_var, "HEX") ; //  "61" "62" "30" "31"
var=varstr.iconv("HEX")

Convert a string of pairs of hexadecimal digits to a string of chars.

varstr: Must be a string of only hex digits 0-9, a-f or A-F.

Returns: A string if all input was hex digits otherwise "".

Dynamic array structure is not preserved. Any field marks prevent conversion.

This function is the exact inverse of oconv("HEX").

After prefixing a "0" to an odd sized input, the size of the output is always precisely half that of the input.

var=varnum.oconv("MX")

Convert number to hexadecimal string.

"MX": Convert and trim leading zeros e.g. oconv(1025, "MX") -> "401"

"MXn": Pad with up to n leading zeros but do not truncate. e.g. oconv(1025, "MX8") -> "00000401"

"MXnT": Pad and truncate to n characters. e.g. oconv(1025, "MX2") -> "01"

"n": Width. 0-9, A-G = 10 - 16.

varnum: A number or dynamic array of numbers. Floating point numbers are rounded to integers before conversion.

Returns: A string of hexadecimal digits or a dynamic array of the same. Elements that are not numeric are left untouched and unconverted.

Dynamic array structure is preserved.

Negative numbers are treated as unsigned 8 byte integers (uint64).

0 -> "00"

1 -> "01"

15 -> "0F"

-1 -> "FFFF" "FFFF" "FFFF" "FFFF" (8 x "FF")

This function is a near inverse of iconv("MX").
let v1 = "14.5]QQ]65535"_var.oconv("MX"); // "F]QQ]FFFF"_var
// or
let v2 = oconv("14.5]QQ]65535"_var, "MX");
var=varstr.iconv("MX")

Convert hexadecimal string to number.

varstr: A string or dynamic array of up to 16 hex digits: 0-9, a-f, A-F.

Returns: An integer or dynamic array of integers. Invalid elements are converted to "".

Dynamic array structure is preserved.

Hex strings are converted to unsigned 8 byte integers (uint64)

Leading zeros are ignored.

"0" -> 0

"00"-> 0

"1" -> 1

Hex "FFFFFFFFFFFFFFFF" (8 x "FF") -> -1.

Hex "7FFFFFFFFFFFFFFF" is the maximum positive integer: 9223372036854775805.

Hex "8000000000000000" is the maximum negative integer: -9223372036854775808.

This function is the exact inverse of oconv("MX").
let v1 = "F]QQ]FFFF"_var.iconv("MX"); // "15]]65535"_var
// or
let v2 = iconv("F]QQ]FFFF", "MX");
var=varnum.oconv("MB")

Number to binary format: Convert number to strings of 1s and 0s

varnum: If not numeric then no conversion is performed and the original value is returned.
let v1 = var(255).oconv("MB"); // 1111'1111
// or
let v2 = oconv(255, "MB");
var=varstr.oconv("TX")

Convert dynamic arrays to standard text format.

Useful for using text editors on dynamic arrays.

FMs -> \n after escaping any embedded NL

VMs -> literal "\" \n

SMs -> literal "\\" \n

etc.
// 1. Backslash in text remains backslash
let v1 = var(_BS).oconv("TX");     // _BS

// 2. Literal "\n" -> literal "\\n" (Double escape any escaped NL chars)
let v2 = var(_BS "n").oconv("TX"); // _BS _BS "n"

// 3. \n becomes literal "\n" (Single escape any NL chars)
let v3 = var(_NL).oconv("TX");     // _BS "n"

// 4. FM -> \n
let v4 = "f1^f2"_var.oconv("TX");  // "f1" _NL "f2"

// 5. VM -> "\" \n
let v5 = "v1]v2"_var.oconv("TX");  // "v1" _BS _NL "v2"

// 6. SM -> "\\" \n
let v6 = "s1}s2"_var.oconv("TX");  // "s1" _BS _BS _NL "s2"

// 7. TM -> "\\\" \n
let v7 = "t1|t2"_var.oconv("TX");  // "t1" _BS _BS _BS _NL "t2"

// 8. ST -> "\\\\" \n
let v8 = "st1~st2"_var.oconv("TX"); // "st1" _BS _BS _BS _BS _NL "st2"
var=varstr.iconv("TX")

Convert standard text format to dynamic array.

Reverse of oconv("TX") above.

</html>

Dim

Use Function Description
Dimensioned Array Construction
Use Function Description
dim d1;Create an undimensioned array of vars pending actual dimensions.
dim d1;
dim d1(nrows, ncols = 1);Create an array of vars with a fixed number of columns and rows. All vars are unassigned.
dim d1(10);
dim d2(10, 3);
dim d1 = d2; // CopyCreate a copy of an array.
 dim d1 = {2, 4, 6, 8};
 dim d2 = d1;
dim d1 = dim(); // Move

Save an array created elsewhere.

Uses C++ "move" semantics.
dim d1 = "f1^f2^f3"_var.split();
dim d1 = {"a", "b", "c" ...}; // Initializer listCreate an array from a list. All elements must be the same type, var, string, double, int, etc.. but all end up as vars which are a flexible type.
dim d1 = {1, 2, 3, 4, 5};
dim d2 = {"A", "B", "C"};
dim d1 = v1;Initialise all elements of an array to some single value or constant. A var, "", 0 etc.
dim d1(10);
d1 = "";
d1.redim(nrows, ncols = 1)

Resize an array to a different number of rows and columns.

Existing data will be retained as far as possible. Any additional elements are unassigned.

Resizing rows to 0 clears all data.

Resizing cols to 0 clears all data and changes its status to "undimensioned".
dim d1;
d1.redim(10, 3);
d1.swap(d2)

Swap one array with another.

Either or both may be undimensioned.
dim d1(5);
dim d2(10);
d1.swap(d2);
Array Access
Use Function Description
var v1 = d1[rowno];
d1[rowno] = v1;
Access and update elements of a one dimensional array using [] brackets
dim d1 = {1, 2, 3, 4, 5};
d1[3] = "X";
let v1 = d1[3]; // "X"
var v1 = d1[rowno, colno];
d1[rowno, colno] = v1;
Access and update elements of an two dimensional array using [] brackets
dim d1(10, 5);
d1 = "";
d1[3, 4] = "X";
let v1 = d1[3, 4]; // "X"
var=d1.rows()

Get the number of rows in the dimensioned array

Returns: A count. Can be zero, indicating an empty array.
dim d1(5,3);
let v1 = d1.rows(); // 5
var=d1.cols()

Get the number of columns in the dimensioned array

Returns: A count. 0 if the array is undimensioned.
dim d1(5,3);
let v1 = d1.cols(); // 3
var=d1.join(delimiter = FM)

Joins all elements into a single delimited string

delimiter: Default is FM.

Returns: A string var.
dim d1 = {"f1", "f2", "f3"};
let v1 = d1.join(); // "f1^f2^f3"_var
Array Mutation
Use Function Description
d1.splitter(str1, delimiter = FM)

Creates or updates the array from a given string.

If the dim array is undimensioned it will be dimensioned with the number of elements that the string has fields.

If the dim array is dimensioned and has more elements than there are fields in the string, the excess array elements are initialised to "". If the record has more fields than there are elements in the array, the excess fields are all left unsplit in the final element of the array.

Predimensioning arrays allows the efficient reuse of arrays in loops and ensures that all elements are assigned values, useful when reading records from db files.

Using undimensioned arrays allows the efficient handling of arrays with a very variable number of elements. e.g. os text files.
dim d1;
d1.splitter("f1^f2^f3"_var); // d1.rows() -> 3  //// Automatically dimensioned.
//
dim d2(10);
d2.splitter("f1^f2^f3"_var); // d2.rows() -> 10 /// Predimensioned. Excess elements become ""
d1.sorter(reverse = false)

Sort the elements of the array in place.

reverse: Defaults to false. If true, then the order is reversed.
dim d1 = "2,20,10,1"_var.split(",");
d1.sorter();
let v1 = d1.join(","); // "1,2,10,20"_var
d1.reverser()Reverse the elements of the array in place.
dim d1 = "2,20,10,1"_var.split(",");
d1.reverser();
let v1 = d1.join(","); // "1,10,20,2"_var
d1.shuffler()Randomly shuffle the order of the elements of the array in place.
dim d1 = "2,20,10,1"_var.split(",");
d1.shuffler();
let v1 = d1.join(","); // random
Array Conversion
Use Function Description
dim=d1.sort(reverse = false)Same as sorter() but returns a new array leaving the original untouched.
dim=d1.reverse()Same as reverser() but returns a new array leaving the original untouched.
dim=d1.shuffle()Same as shuffler() but returns a new array leaving the original untouched.
Array DB I/O
Use Function Description
d1.write(dbfile, key)

Writes a db file record created from an array.

Each element in the array becomes a separate field in the db record. Any redundant trailing FMs are suppressed.
dim d1 = "Client GD^G^20855^30000^1001.00^20855.76539"_var.split();
let file = "xo_clients", key = "GD001";
if (not deleterecord("xo_clients", "GD001")) {}; // Cleanup first
d1.write(file, key);
// or
write(d1 on file, key);
ifd1.read(dbfile, key)

Read a db file record into an array.

Each field in the database record becomes a single element in the array.

Returns: True if the record exists or false if not,

If the array is predimensioned then any excess array elements are initialised to "" and any excess record fields are left unsplit in the final array element. See dim splitter for more info.

If the array is not predimensioned (rows and cols = 0) then it will be dimensioned to have exactly the same number of rows as there are fields in the record being read.
dim d1(10);
let file = "xo_clients", key = "GD001";
if (not d1.read(file, key)) ... // d1.join() -> "Client GD^G^20855^30000^1001.00^20855.76539^^^^"_var
// or
if (not read(d1 from file, key)) ...
Array OS I/O
Use Function Description
ifd1.oswrite(osfilename, codepage = "")

Creates an entire os text file from an array

Each element of the array becomes one line in the os file delimited by \n

Any existing os file is overwritten and replaced.

codepage: Optional: Data is converted from UTF8 to the required codepage/encoding before output. If the conversion cannot be performed then return false.

Returns: True if successful or false if not.
dim d1 = "aaa=1\nbbb=2\nccc=3\n"_var.split("\n");
if (not osremove("xo_conf.txt")) {}; // Cleanup first
let osfilename = "xo_conf.txt";
if (not d1.oswrite(osfilename)) ...
// or
if (not oswrite(d1 on osfilename)) ...
ifd1.osread(osfilename, codepage = "")

Read an entire os text file into an array.

Each line in the os file, delimited by \n or \r\n, becomes a separate element in the array.

Existing data in the array is lost and the array is redimensioned to the number of lines in the input data.

codepage: Optional. Data will be converted from the specified codepage/encoding to UTF8 after being read. If the conversion cannot be performed then return false.

Returns: True if successful or false if not.

If the first \n in the file is \r\n then the whole file will be split using \r\n as delimiter.
dim d1;
let osfilename = "xo_conf.txt";
if (not d1.osread(osfilename)) ... // d1.join("\n") -> "aaa=1\nbbb=2\nccc=3\n"_var0
// or
if (not osread(d1 from osfilename)) ...

</html>

Exodus Program

Use Function Description
Select Lists
Use Function Description
ifselect(sortselectclause_or_filehandle = "")

Create an active select list using a natural language sort/select command.

This and all the following exoprog member functions work on an environment variable CURSOR.

Identical functions are available directly on plain var objects but vars have less functionality regarding dictionaries and environment variables which are built-in to exoprog.

Returns: True if an active select list was created, false otherwise.

In the following examples, various environment variables like RECORD, ID and MV are used instead of declaring and using named vars. In actual code, either may be freely used.
select("xo_clients by name by type with type 'A' 'B' and with balance between 0 and 2000");
if (readnext(ID)) ... ok
ifselectkeys(keys)Create an active select list from some given keys.
selectkeys("SB001^JB001^JB002"_var);
if (readnext(ID)) ... ok // ID -> "SB001"
ifhasnext()Check if a select list is active.
if (hasnext()) ... ok
ifreadnext(out key)

Get the next key from an active select list.

key: [out] A string. Typically the key of a db file record.

Returns: True if an active select list was available and the next key in the list was obtained.
selectkeys("SB001^JB001^JB002"_var);
if (readnext(ID)) ... ok // ID -> "SB001"
ifreadnext(out key, out valueno)

Get the next key and value number pair from an active select list.

key: [out] A string. Typically the key of a db file record.

valueno: [out] Is only available in select lists that have been created by sort/select commands that refer to multi-valued db dictionary fields where db records have multiple values for a specific field. In this case, a record key will appear multiple times in the select list since each multivalue is exploded for the purpose of sorting and selecting. This can be viewed as a process of "normalising" multivalues so they appear as multiple records instead of being held in a single record.

Returns: True if an active select list was available and the next key in the list was obtained.
selectkeys("SB001]2^SB001]1^JB001]2"_var);
if (readnext(ID, MV)) ... ok // ID -> "SB001" // MV -> 2
ifreadnext(out record, out key, out valueno)

Get the next record, key and value no from an active select list.

record: [out] Is only available in select lists that have been created with the final (R) option. Otherwise the record will be returned as an empty string and must be obtained using a db read() function.

key: [out] A string. Typically the key of a db file record.

valueno: [out] Is only available in select lists that have been created by sort/select commands that refer to multi-valued db dictionary fields where db records have multiple values for a specific field.

Returns: True if an active select list was available and the next key in the list was obtained.
select("xo_clients by name (R)");
if (readnext(RECORD, ID, MV)) ... ok;
assert(not RECORD.empty());
pushselect(out cursor)

Saves a pointer to the currently active select list.

This allows another select list to be activated and used temporarily before the original select list is reactivated.

cursor: [out] A var that can be passed later on to the popselect() function to reactivate the saved list.
select("xo_clients by name");
var saved_xo_clients_cursor;
pushselect(saved_xo_clients_cursor);
//
// ... work with another select list ...
//
popselect(saved_xo_clients_cursor); // Reactivate the original select list.
popselect(cursor)

Re-establish an active select list saved by pushselect().

cursor: A var created by the pushselect() function.

See pushselect() for more info.
clearselect()

Deactivate an active select list.

If no select list is active then nothing is done.
clearselect();
ifdeleterecord(filename)

Use an active select list to delete db records.

Returns: False if any records could not be deleted.

Contrast this function with the two argument "deleterecord(file, key)" function that deletes a single record.
if (select("xo_clients with type 'Q' and with balance between 0 and 100")) {
  if (deleterecord("xo_clients")) ...
}
ifdeleterecord(dbfile, key)Delete a single database file record.
let file = "xo_clients", key = "QQ001";
write("" on file, key);
if (not deleterecord(file, key)) ...
// or
write("" on file, key);
if (not file.deleterecord(key)) ...
ifsavelist(listname)

Save a currently active select list under a given name.

After saving, the list is no longer active and hasnext() will return false.

Returns: True if an active select list was saved, false if there was no active select list.

Lists are saved as a record in the "lists" file.
selectkeys("SB001^SB002"_var);
if (not savelist("my_list")) ...
ifgetlist(listname)

Reactivate a saved select list of a given name.

A saved list is obtained from the "lists" file and activated.

Returns: True if an active select list was successfully reactivated, otherwise false.
if (not getlist("my_list")) ...
ifdeletelist(listname)

Remove a saved select list by name.

A saved list is deleted from the "lists" file.
if (not deletelist("my_list")) ...
Perform/Execute
Use Function Description
var=perform(command_line)

Run an exodus program/library's main function using a command like syntax similar to that of executable programs.

A "command line" is passed to the program/library in the usual COMMAND, SENTENCE and OPTIONS environment variables instead of function arguments.

The program/library's main function should have zero arguments. Performing a program/library function with main arguments results in them being unassigned and in some case core dump may occur.

The following environment variables are initialised on entry to the main function of the program/library. They are preserved untouched in the calling program.

SENTENCE, COMMAND, OPTIONS: Initialised from the argument "command_line".

RECUR0, RECUR1, RECUR2, RECUR3, RECUR4 to "".

ID, RECORD, MV, DICT initialised to "".

LEVEL is incremented by one.

All other environment variables are shared between the caller and callee. There is essentially only one environment in any one process or thread.

Any active select list is passed to the performed program/library and can be consumed by it. Conversely any active select list created by the performed program/library will be returned to the calling program. In other words, both the performing and the performed programs/libraries share a single active select list environment. This is different from execute() which gets its own private active select list, initially inactive.

command_line: The first word of this argument is used as the name of the program/library to be loaded and run. command_line is used to initialise the SENTENCE, COMMAND and OPTIONS environment variables.

Returns: Whatever var the program/library returns, or "" if it calls stop() or abort(()".

The return value can be ignored and discarded without any compiler warning.

Exodus program/libraries may also be called directly using conventional function calling syntax. To call an exodus program/library called progname using either the syntax "call progname(args...);" or "var v1 = progname(args...);" you must "#include " after the "programinit()" or "libraryinit()" lines in your program/library.
var=execute(command_line)

Run an exodus program/library's main function.

Identical to perform() but any currently active select list in the calling program/library is not accessible to the executed program/library and is preserved in the calling [program as is. Any select list created by the executed library is discarded when it terminates.
chain(command_line)

Run an exodus program/library's main function after closing the current program.

Identical to perform() except that the current program closes first.
var=libinfo(libname)Check if a lib exists to be performed/executed or called.
Program Termination
Use Function Description
stop(message = "")

Stop the current exodus program/library normally and return to the parent exodus program/library, or return to the operating system if none.

Calling stop() in an exodus OS command line executable program, or in a function called from the same, will terminate the OS process with an error status of 0 which is generally considered to indicate success.

Calling stop() in a performed or executed exodus program/library, or in a function called from the same, will terminate the program/library being executed and return to the exodus program that performed or executed it.
abort(message = "")

Abort the current exodus program/library abnormally and return to the parent exodus program/library, or return to the operating system if none.

Similar to stop() but, if terminating the OS process, then return an error status of 1 which is generally considered to be an indication of failure.
abortall(message = "")

Abort the current exodus program/library abnormally and return to the parent exodus program/library, or return to the operating system if none.

Similar to abort() but, if terminating the OS process, then return an error status of 2 which is generally considered to be an indication of failure.
logoff(message = "")
DB File Dictionaries
Use Function Description
var=calculate(dictid)

given dictid reads dictrec from DICT file and extracts from RECORD/ID or calls library

called dict+DICT function dictid not const so we can mess with the library?
var=calculate(dictid, dictfile, id, record, mv = 0)
var=xlate(filename, key, fieldno_or_name, mode)
I/O Conversion
Use Function Description
var=oconv(input, conversion)

iconv/oconv with access to exoprogram's environment variables.

exoprog's iconv/oconv have the ability to call custom functions like "[funname,args...]"

[NUMBER] // built-in. See doc below.

[DATE] // built-in. See doc below.

[DATEPERIOD] e.g. [DATEPERIOD,1] [DATEPERIOD,1,12]

[DATETIME] e.g. [DATETIME,4*,DOS] [DATETIME,4*,MTS] [DATETIME,4*]

[TIME2] e.g. [TIME2,MT] [TIME2,MTS] [TIME2,MTS48]

var=iconv(input, conversion)
Ioconv Date/Time
Use Function Description
var=iconv|oconv(var, "[DATE]")

Use iconv/oconv code "[DATE,args]" when you want date conversion to depend on the environment variable DATEFMT, particularly its American/International setting. Otherwise use ordinary "D" conversion codes directly for slightly greater performance.

var: [oconv] An internal date (a number).

Returns: [oconv] A readable date in text format depending on "[DATE,args]" e.g. "31 DEC 2020" "31/12/2020" "12/31/2020"

var: [iconv] A date in text format as above.

Returns: [iconv] An internal date (a number) or "" if the input could not be understood as a valid date.

args: If args is empty then DATEFMT is used as the conversion code. If args starts with "D" then args is used as the conversion codes but any E option in DATEFMT is appended. If args does not start with "D" then args are appended to DATEFMT, a "Z" option is appended, and the result used as the conversion code. A "*" option is equivalent to a second "Z" option.

If you are calling iconv/oconv in code and DATEFMT is adequate for your needs then pass it directly as a function argument e.g. 'var v1 = iconv|oconv(v2, DATEFORMAT);' instead of indirectly like 'var v1 = iconv|oconv(v2, "[DATE]");'.
let v1 = iconv("JAN 9 2020", "D");
assert(oconv(v1, "[DATE]"   ) == " 9/ 1/2020");  // "D/EZ" or "[DATE,D]" equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
assert(oconv(v1, "[DATE,4]" ) == " 9/ 1/2020");  // "D4Z"  equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
assert(oconv(v1, "[DATE,*4]") == "9/1/2020");    // "D4ZZ" equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)
assert(oconv(v1, "[DATE,*]" ) == "9/1/20");      // "DZZ"  equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)
var=iconv|oconv(var, "[NUMBER]")

Use iconv/oconv "[NUMBER,args]" either when your numbers have currency or unit code suffixes or when you want number conversion to depend on the environment variable BASEFMT to determine thousands separator and decimal point. Otherwise use ordinary "MD" conversion codes directly for slightly greater performance.

Formatting for numbers with optional currency code/unit suffix and is sensitive to the International or European setting in BASEFMT regarding use of commas or dots for thousands separators and decimal points.

Primarily used for oconv() but can be used in reverse for iconv.

var: A number with an optional currency code or unit suffix. e.g. "12345.67USD"

Returns: A formatted number with thousands separated conventionally e.g. "12.345.67USD".

iconv/oconv("[NUMBER]") oconv leaves ndecimals untouched as in the input. iconv see below.

iconv/oconv("[NUMBER,2]") Specified number of decimal places

iconv/oconv("[NUMBER,BASE]") Decimal places as per BASEFMT

iconv/oconv("[NUMBER,*]") Leave decimal places untouched as in the input

iconv/oconv("[NUMBER,X]") Leave decimal places untouched as in the input

iconv/oconv("[NUMBER,2Z]") Z (suppress zero) combined with any other code for oconv results in empty output "" instead of "0.00" in case of zero input.

Empty input "" gives empty output "".

All leading, trailing and internal spaces are removed from the input.

A trailing currency or unit code is ignored and returned on output.

An exodus number is an optional leading + or - followed by one or more decimal digits 0-9 with a single optional decimal point placed anywhere.

If the input is non-numeric then "" is returned and STATUS set to 2. In the case of oconv with multiple fields or values each field or value is processed separately but STATUS is set to 2 if any are non-numeric.

iconv removes and oconv adds thousand separator chars. The thousands separator is "," if BASEFMT starts with "MD" or "." if it starts with "MC".

oconv:

Add thousands separator chars and optionally standardise the number of decimal places.

Multiple numbers in fields, values, subvalues etc. can be processed in one string.

Any leading + character is preserved on output.

Z suppresses zeros and returns empty string "" instead.

Special format "[NUMBER,ndecs,move_ndecs]": move_ndecs causes decimal point to be shifted left if positive or right if negative.

var v1 = oconv("1234.5USD", "[NUMBER,2]"); // "1,234.50USD" // Comma added and decimal places corrected.

iconv:

Remove all thousands separator chars and optionally standardise the number of decimal places.

If ndecs is not specified in the "[NUMBER]" pattern then ndecs is taken from the current RECORD using dictionary code NDECS if DICT is available otherwise it uses ndecs from BASEFMT.

iconv only handles a single field/value.

Optional prefix of "1/" or "/" causes the reciprocal of the number to be used. e.g. "1/100" or "/100" -> "0.01".
var v1 = iconv("1,234.5678USD", "[NUMBER]"); // "1234.57USD" // Comma removed
var=amountunit(input0, out unitx)

Split amount+currency code/unit string into number and currency code/unit.

var: "123.45USD"

Returns: e.g. "123.45"

unitx: [out] e.g. "USD"
var=amountunit(input0)
Time/Date Utilities
Use Function Description
var=timedate2()

Returns: Text of date and time in users time zone

e.g. "2MAR2025 11:52AM"

Offset from UTC by TZ seconds.
getdatetime(out user_date, out user_time, out system_date, out system_time, out UTC_date, out UTC_time)

Returns: User, server and UTC date and time

User date and time is determined by adding the environment variable TZ.f(1)'s TZ offset (in seconds) to UTC date/time obtained from the operating system.

"system" date and time is normally the same as UTC date/time and is determined by adding the environment variable TZ.f(2)'s TZ offset (in seconds) to UTC date/time obtained from the operating system.

var=elapsedtimetext()

Get text of elapsed time since environment variable TIMESTAMP was initialised with ostimestamp() at program/thread startup.

TIMESTAMP can be updated using ostimestamp() as and when desired.
var v1 = elapsedtimetext(); // e.g. "< 1ms"
var=elapsedtimetext(timestamp1, timestamp2)Get text of elapsed time between two timestamps
let v1 = elapsedtimetext(0, 0.55);  // "13 hours, 12 mins"
let v2 = elapsedtimetext(0, 0.001); // "1 min, 26 secs"
Terminal I/O Utilities
Use Function Description
note(msg, options, io response)

If stdin is a terminal, output a message to stdout and optionally pause processing and request a response from the user, otherwise set the response to "" and continue.

options: R = Response requested. C upper case response.
var response;
// call note("Enter something", "RC", response);
note(msg)Output a message to stdin and continue.
call note("Hello world.");
var=decide(question, options = "")

If stdin is a terminal, pause processing, list some given options to stdout and request the user to make a choice, otherwise set the response to "" and continue.

Returns: The chosen option (value not number) or "" if the user cancelled.
var=decide(question, options, out reply, defaultreply = 1)

Same as decide() above but extended.

defaultreply: A default option if the user presses Enter.

reply: [out] The option number that the user chose or "" if they cancelled.
ifesctoexit()

If stdin is a terminal, check if a key has been pressed and, if so, pause execution and ask the user to confirm if they want to escape/cancel or resume processing.

Returns: True if a key has been pressed and the user confirms to escape/cancel. False if no key has been pressed or the user chooses to resume and not escape/cancel.
var=AT(code)

Get a string to control terminal operation.

Returns: A string to be output to the terminal in order to accomplish the desired operation.

The terminal protocol is xterminal.

code:

n Position the cursor at column number n

0 Position the cursor at column number 0

-1 Clear the screen and home the cursor

-2 Position the cursor at the top left home (x,y = 0,0)

-3 Clear from the cursor at the end of screen

-4 Clear from cursor to end of line

-40 Position the cursor at columnno 0 and clear to end of line
var=AT(x, y)

Get a terminal cursor positioning string.

Returns: A string to be output to the terminal to position the cursor at the desired screen x and y position.

The terminal protocol is xterminal.
ifgetcursor(out cursor, delayms = 3000, max_errors = 0)

Get the position of the terminal cursor.

cursor: [out] If stdin is a terminal, an FM delimited string containing the x and y coordinates of the current terminal cursor.

If stdin is not a terminatl then an empty string "" is returned.

The cursor additionally contains a third field which contains the delay in ms from the terminal.

The FM delimited string returned can be later passed to setcursor() to reposition the cursor back to its original position or it can be parsed and used accordingly.

delayms: Default 3000ms. The maximum time to wait for terminal response.

max_errors: Default is 0. If not zero, reset the number of times to error before automatically disabling getcursor(). max_errors is initialised to 3. If negative then max_errors has the the effect of disabling all future calls to getcursor().

In case the terminal fails to respond correctly within the required timeout, or is currently disabled due to too many failures, or has been specifically disabled then the returned "cursor" var contains a 4th field:

TIMEOUT - The terminal failed to respond within the timeout.

READ_ERROR - Failed to read terminal response.

INVALID_RESPONSE - Terminal response invalid.

SETUP_ERROR - Terminal setup failed.

DISABLED - Terminal is disabled due to more errors than the maximum currently set.
var cursor;
if (isterminal() and not getcursor(cursor)) ... // cursor becomes something like "0^20^0.012345"_var
var=getcursor()

Get the position of the terminal cursor.

For more info see the main getcursor() function above.
let cursor = getcursor(); // If isterminal() then cursor becomes something like "0^20^0.012345"_var
setcursor(cursor_coordinates)

If stdin is a terminal, position the cursor at x and y as per the given coordinates.

cursor_coordinates: An FM delimited string containing the x and y coordinates of the terminal cursor as can be obtained by getcursor().
if (isterminal()) {
    let cursor = getcursor(); // Save the current cursor position.
    TRACE(cursor)             // Show the saved cursor position.
    print(AT(0,0));           // Position the cursor at 0,0.
    setcursor(cursor);        // Restore its position
}
Array Utilities
Use Function Description
var=invertarray(input, pad = false)

Dynamic array fields become values and vice versa

Returns: The inverted dynamic array.

pad: If true then on return, all fields will have the same number of values with superfluous trailing VMs where necessary.
let v1 = "a]b]c^1]2]3"_var;
let v2 = invertarray(v1); // "a]1^b]2^c]3"_var
sortarray(io array, fns = "", order = "")

Sorts fields of multivalues of dynamic arrays in parallel

fns: VM separated list of field numbers to sort in parallel based on the first field number

order:

AL Ascending - Left Justified - Alphabetic

DL Descending - Left Justfiied - Alphabetic

AR Ascending - Right Justified - Numeric

DR Descending - Right Justified - Numeric
var v1 = "f1^10]20]2]1^ww]xx]yy]zz^f3^f4"_var;  // fields 2 and 3 are parallel multivalues and currently unordered.
sortarray(v1, "2]3"_var, "AR"); // v1 -> "f1^1]2]10]20^zz]yy]ww]xx^f3^f4"_var
Record Locking
Use Function Description
iflockrecord(filename, io file, keyx, recordx, waitsecs = 0, allowduplicate = false)Does not actually return record
iflockrecord(filename, io file, keyx)
ifunlockrecord(filename, io file, key)
ifunlockrecord()

</html>