Functions
Contents:
- Var Creation
- Arithmetical Operators
- Dynamic Array Creation, Access And Update
- String Creation
- String Scanning
- String Conversion - Non-Mutating - Chainable
- String Mutation - Standalone Commands
- I/O Conversion
- Dynamic Array Functions
- Dynamic Array Filters
- Dynamic Array Mutators Standalone Commands
- Dynamic Array Search
- Database Access
- Database Management
- Database File I/O
- Database Sort/Select
- OS Time/Date
- OS File I/O
- OS Directories
- OS Shell/Environment
- Output
- Input
- Math/Boolean
- I/O Conversion Codes
Var Creation
Use | Function | Description |
---|---|---|
| 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")) ...
// Exodus keywords: C++ declarations:
// Non-Const Const Non-Const Const
// ----------------- ----------------------
// Variable: var let var const var
// Reference: out in var& const var&
| |
| 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
| |
|
| Check if a var has been assigned a value. return: True if the var is assigned, otherwise false |
|
| Check if a var has not been assigned a value; return: True if the var is unassigned, otherwise false |
|
| Copy a var or, if it is unassigned, copy a default value. return: 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() |
| If a var is unassigned, assign a default value. 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");
| |
| 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);
| |
|
| Move a var into another. Shallow copy of var data and take ownership of the moved var's string if any. 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);
|
|
| Return 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);
|
|
| Return a string describing internal data of a var. If the str is located on the heap then its address is given. typ:
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 |
---|---|---|
|
| Check if a var is numeric. return: 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
|
|
| Return a copy of the var if it is numeric or 0 otherwise. Allow working numerically with data that may be non-numeric. return: A guaranteed numeric var
var v1 = "123.45"_var.num(); // 123.45
var v2 = "abc"_var.num() + 100; // 100
|
|
| Addition Any attempt 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
|
|
| Subtraction |
|
| Multiplication |
|
| Division |
|
| Modulus |
| Self addition
var v1 = 0.1;
v1 += 0.2; // 0.3
| |
| Self subtraction | |
| Self multiplication | |
| Self division | |
| Self modulus | |
| Post increment
var v1 = 3;
var v2 = v1 ++; // v2 -> 3 // v1 -> 4
| |
| Post decrement
var v1 = 3;
var v2 = v1 --; // v2 -> 3 // v1 -> 2
| |
| Pre increment
var v1 = 3;
var v2 = ++ v1; // v2 -> 4 // v1 -> 4
| |
| Pre decrement
var v1 = 3;
var v2 = -- v1; // v2 -> 2 // v1 -> 2
|
Dynamic Array Creation, Access And Update
Use | Function | Description |
---|---|---|
|
| Literal suffix "_var". Allow dynamic arrays to be seamlessly embedded in code using a predefined set of visible equivalents of unprintable field mark characters as follows: Visible equivalents:
var v1 = "f1^f2^v1]v2^f4"_var; // "f1" _FM "f2" _FM "v1" _VM "v2" _FM "f4"
|
| Code a dynamic array var as as 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
| |
|
| 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.
|
|
| 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 |
---|---|---|
|
| 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"
|
| String self concatention ^= (append) var v1 = "aa";
v1 ^= 22; // v1 -> "aa22"
| |
|
| Round a number. 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. return: 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"
|
|
| Get a char. num: An integer 0-255. return: 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);
|
|
| Get a Unicode character. num: A Unicode Code Point (Number) return: A single Unicode character in UTF8 encoding.
let v1 = var::textchr(171416); // "𩶘" // or "\xF0A9B698"
// or
let v2 = textchr(171416);
|
|
| Get a Unicode character name unicode_code_point: 0 - 0x10FFFF. return: 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);
|
|
| Get a string of repeated substrings. var: The substring to be repeated num: How many times to repeat the substring return: A string
let v1 = "ab"_var.str(3); // "ababab"
// or
let v2 = str("ab", 3);
|
|
| Get a string as a given number of spaces. nspaces: The number of spaces required. return: A string of space chars.
let v1 = var::space(3); // "␣␣␣"
// or
let v2 = space(3);
|
|
| Get a number written out in words insteads of digits. return: A string. 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 |
---|---|---|
|
| Get a single char from a string. pos1: First char is 1. Last char is -1. return: 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); // ""
|
|
| Get the char number of a char. return: 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");
|
|
| Get the Unicode Code Point of a Unicode character. var: A UTF-8 string. Only the first Unicode character is considered. return: 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("Γ");
|
|
| Get the length of a source string in number of chars. return: A number
let v1 = "abc"_var.len(); // 3
// or
let v2 = len("abc");
|
|
| Check if the var is an empty string. return: 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
|
|
| Count the number of output columns required for a given source string. return: A number Allow wide multi-column Unicode characters that occupy more than one space in a text file or terminal screen. Reduce 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🤡");
|
|
| Count the number of Unicode code points in a source string. return: A number.
let v1 = "Γιάννης"_var.textlen(); // 7
// or
let v2 = textlen("Γιάννης");
|
|
| Count the number of fields in a source string. sepstr: The separator character or substr that delimits individual fields. return: 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", "*");
|
|
| Count the number of occurrences of a given substr in a source string. substr: The substr to count. return: 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", "*");
|
|
| Check if a source string starts with a given prefix (substr). prefix: The substr to check for. return: True if the source string starts with the given prefix. Always returns false if suffix is "". DIFFERS from c++, javascript, python3. See contains() for more info.
if ("abc"_var.starts("ab")) ... true
// or
if (starts("abc", "ab")) ... true
|
|
| Check if a source string ends with a given suffix (substr). suffix: The substr to check for. return: True if the source string ends with given suffix. Always 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
|
|
| Check if a given substr exists in a source string. substr: The substr to check for. return: True if the source string starts with, ends with or contains the given substr. Always returns false if substr is "". DIFFERS from c++, javascript, python3. See contains() for more info. 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
|
|
| 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. return: 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");
|
|
| Find the nth occurrence of a substr in a source string. substr: The string to search for. return: char position (1 based) or 0 if not present.
let v1 = "abcabc"_var.indexn("bc", 2); // 5
// or
let v2 = indexn("abcabc", "bc", 2);
|
|
| Find the position of substr working backwards Start at the end and work backwards. substr: The string to search for. return: 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");
|
|
| Find all matches of a given regular expression. return: 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:
char ranges like a-z are locale sensitive if ECMAScript regex_options:
|
|
| Ditto |
|
| 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 or 0 if no more matches. return: 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");
|
|
| Ditto starting from first char |
|
| Ditto given a rex |
|
| Ditto starting from first char. |
|
| Get a hash of a source string. modulus: The result is limited to [0, modulus) return: 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 |
---|---|---|
|
| Convert to upper case
let v1 = "Γιάννης"_var.ucase(); // "ΓΙΆΝΝΗΣ"
// or
let v2 = ucase("Γιάννης");
|
|
| Convert to lower case
let v1 = "ΓΙΆΝΝΗΣ"_var.lcase(); // "γιάννης"
// or
let v2 = lcase("ΓΙΆΝΝΗΣ");
|
|
| Convert to title case. return: Original source string with the first letter of each word is capitalised.
let v1 = "γιάννης παππάς"_var.tcase(); // "Γιάννης Παππάς"
// or
let v2 = tcase("γιάννης παππάς");
|
|
| Convert to folded case. Case folding is the process of converting text to a case independent representation. return: The source string standardised in a way to enable consistent indexing and searching, 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");
|
|
| 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");
|
|
| 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. return: 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");
|
|
| Reduce all types of field mark chars by one level. Convert all FM to VM, VM to SM etc. return: 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);
|
|
| Increase all types of field mark chars by one level. Convert all VM to FM, SM to VM etc. return: 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;
|
|
| 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);
|
|
| Wrap in double quotes.
let v1 = "abc"_var.quote(); // "\"abc\""
// or
let v2 = quote("abc");
|
|
| Wrap in single quotes.
let v1 = "abc"_var.squote(); // "'abc'"
// or
let v2 = squote("abc");
|
|
| Remove one pair of surrounding double or single quotes.
let v1 = "'abc'"_var.unquote(); // "abc"
// or
let v2 = unquote("'abc'");
|
|
| 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␣␣");
|
|
| Ditto but only leading.
let v1 = "␣␣a1␣␣b2␣c3␣␣"_var.trimfirst(); // "a1␣␣b2␣c3␣␣"
// or
let v2 = trimfirst("␣␣a1␣␣b2␣c3␣␣");
|
|
| Ditto but only trailing.
let v1 = "␣␣a1␣␣b2␣c3␣␣"_var.trimlast(); // "␣␣a1␣␣b2␣c3"
// or
let v2 = trimlast("␣␣a1␣␣b2␣c3␣␣");
|
|
| 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␣␣");
|
|
| Get the first char of a string. return: 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");
|
|
| Get the last char of a string. return: 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");
|
|
| Get the first n chars of a source string. length: The number of chars (bytes) to get. return: 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);
|
|
| 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);
|
|
| 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);
|
|
| Insert a substr at an given position after removing a given number of chars. pos1:
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");
|
|
| 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");
|
|
| 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");
|
|
| 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", '.');
|
|
| Remove one trailing char. Equivalent to var[-1, 1] = "" in Pick OS
let v1 = "abc"_var.pop(); // "ab"
// or
let v2 = pop("abc");
|
|
| Copy one or more consecutive fields from a string. delimiter: A Unicode character. fieldno: The first field is 1, the last field is -1. return: 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);
|
|
| |
|
| 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. return: 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"
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,"
|
|
| substr version 1. Copy a substr of length chars from a given a starting char position. return: 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"
|
|
| Abbreviated alias of substr version 1. |
|
| substr version 2. Copy a substr from a given char position up to the end of the source string return: 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);
|
|
| Shorthand alias of substr version 2. |
|
| substr version 3. Copy a substr from a given char position up to (but excluding) any one of some given delimiter chars return: 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.
|
|
| Shorthand alias of substr version 3. |
|
| substr version 4. Copy a substr from a given char position up to (but excluding) the next field mark char (RM, FM, VM, SM, TM, ST). return: 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.
|
|
| Shorthand alias of substr version 4. |
|
| 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");
|
|
| Ditto for Unicode code points.
let v1 = "a🤡b😀c🌍d"_var.textconvert("🤡😀", "👋"); // "a👋bc🌍d"
// or
let v2 = textconvert("a🤡b😀c🌍d", "🤡😀", "👋");
|
|
| 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");
|
|
| 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
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'");
|
|
| Replace substrings using a regular expression and a custom function. Allow complex string conversions. repl_func: A function with arguments (in match_str) that returns a var to replace match_str. May be an inline anonymous lambda function (capturing or non-capturing). 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.
let v1 = R"(--\0x3B--\0x2F--)"; // Hex escape codes.
let v2 = v1.replace(
R"(\\0x[0-9a-fA-F]{2,2})"_rex, // Find \0xFF.
[](auto match_str) {return match_str.cut(3).iconv("HEX");} // Decode to a char.
);
assert(v2 == "--;--/--");
// Reformat dates using groups.
let v3 = "Date: 03-15-2025";
let v4 = v3.replace(
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(v4 == "Date: 2025-03-15");
|
|
| Remove duplicate fields, values or subvalues. From a dynamic array.
let v1 = "a1^b2^a1^c2"_var.unique(); // "a1^b2^c2"_var
// or
let v2 = unique("a1^b2^a1^c2"_var);
|
|
| Reorder fields, values or subvalues. In a dynamic array. 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);
|
|
| 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);
|
|
| Randomise the order of fields in an FM, VM separated list
let v1 = "20^10^2^1^1.1"_var.randomize(); /// e.g. "2^1^20^1.1^10" (random order depending on initrand())
// or
let v2 = randomize("20^10^2^1^1.1"_var);
|
|
| Split a delimited string into a dynamic array. Replace separator chars with FM chars except inside double or single quotes and ignoring escaped quotes \" \' return: A dynamic array Can be used to process CSV data.
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", ',');
|
|
| Split a delimited string into a dim array. Delimiter: Can be multibyte Unicode. return: 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);
|
|
| |
|
|
String Mutation - Standalone Commands
Use | Function | Description |
---|---|---|
| To 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);
| |
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
| ||
|
I/O Conversion
Use | Function | Description |
---|---|---|
|
| Convert internal data to output external display format. convstr: A conversion code or pattern. See ICONV/OCONV PATTERNS return: The data in external display format or, if the data is invalid and cannot converted, most conversions return the original data UNCONVERTED. throw: VarNotImplemented if convstr is invalid
let v1 = var(30123).oconv("D/E"); // "21/06/2050"
// or
let v2 = oconv(30123, "D/E");
|
|
| Convert external data to internal format. convstr: A conversion code or pattern. See ICONV/OCONV PATTERNS return: The data in internal format or, if the data is invalid and cannot be converted, most conversions return the EMPTY STRING "" throw: VarNotImplemented if convstr is invalid
let v1 = "21 JUN 2050"_var.iconv("D/E"); // 30123
// or
let v2 = iconv("21 JUN 2050", "D/E");
|
|
| 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));
|
|
| Convert from codepage encoded text to UTF-8 encoded exodus text codepage: e.g. Codepage "CP1124" (Ukrainian). Use Linux command "iconv -l" for a 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
|
|
| Convert 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 |
---|---|---|
|
| 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"
|
|
| 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);
|
|
| Update (replace or insert) a specific subvalue in a dynamic array. 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. |
|
| Update (replace or insert) a specific value in a dynamic array. |
|
| Update (replace or insert) a specific field a dynamic array. |
|
| Insert a subvalue in a dynamic array. Same as var.inserter() function but returns a new string instead of updating a variable in place. |
|
| Insert a value in a dynamic array. |
|
| Insert a field in a dynamic array. |
|
| Remove a field, value or subvalue from a dynamic array. 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 |
---|---|---|
|
| Sum up multiple values in a dynamic array. Whatever is the lowest level is summed up into a 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);
|
|
| Sum up everything in a dynamic array.
let v1 = "1]2]3^4]5]6"_var.sumall(); // 21
// or
let v2 = sumall("1]2]3^4]5]6"_var);
|
|
| Sum all fields using a given delimiter.
let v1 = "10,20,30"_var.sum(","); // 60
// or
let v2 = sum("10,20,30", ",");
|
|
| Calculate basic statistics include stddev. return: An FM delimited string containing n, tot, min, max, tot, mean and stddev strvar: A dynamic array containing numbers using any field, value or subvalue mark delimiters.
let v1 = "-11.2^0^11.5^12^13.9^14"_var.stddev(); // "6^40.2^-11.2^14^6.7^9.32344714506"_var
// or
let v2 = stddev("-11.2^0^11.5^12^13.9^14"_var);
|
|
| Binary ops on parallel multivalues opcode:
let v1 = "10]20]30"_var.mv("+","2]3]4"_var); // "12]23]34"_var
|
Dynamic Array Mutators Standalone Commands
Use | Function | Description |
---|---|---|
| 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");
| |
| Replace a specific value 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");
| |
| Replace a specific subvalue 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");
| |
| Insert a specific field in a dynamic array All other fields are moved 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");
| |
| Insert a specific value in a dynamic array. All other values are moved 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");
| |
| Insert a specific subvalue in a dynamic array. All other subvalues are moved 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");
| |
| Remove a specific field, value, or subvalue from a dynamic array. All other fields, values, or subvalues are moved down.
var v1 = "f1^v1]v2}s2}s3^f3"_var;
v1.remover(2, 2); // "f1^v1^f3"_var
// or
remover(v1, 2, 2);
|
Dynamic Array Search
Use | Function | Description |
---|---|---|
|
| locate substr in dynamic array Search unordered fields, values and/or subvalues. With only the substr argument provided, locate searches regardless of the field mark delimiters present. return: The field, value or subvalue number if found or 0 if not. Fields are counted regardless of delimiter. 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
|
|
| locate substr in values. Search unordered VM delimited string. valueno[out]: Value number if found or the max value number + 1 if not. If not found then valueno [out] is suitable for creating a new value. return: True if found or False if not.
var valueno;
if ("UK]US]UA"_var.locate("US", valueno)) ... ok // valueno -> 2
// or
if (locate("US", "UK]US]UA"_var,valueno)) ... ok
|
|
| locate substr in dynamic array. Search in an unordered dynamic array. fieldno: If fieldno is non-zero then search the specified field number otherwise, if fieldno is 0, search using FM as delimiter. valueno: If provided, search the specified value number for a subvalue. num[out]: If found, the field, value or subvalue number where it was found. If not found, the max field, value or subvalue number + 1. If not found then num [out] is suitable for creating a new field, value or subvalue. return: True if found or False if not.
var num;
if ("f1^f2v1]f2v2]s1}s2}s3}s4^f3^f4"_var.locate("s4", num, 2, 3)) ... ok // num -> 4 // Return true
|
|
| locate substr in ordered dynamic array locateby() without fieldno or valueno arguments, searches ordered values separated by VM chars. Data must already be in the correct order for searching to work properly. ordercode:
return: True if found, otherwise false. valueno[out]: Either the value no found or the correct value no for inserting the substr
var valueno; if ("aaa]bbb]ccc"_var.locateby("AL", "bb", valueno)) ... // valueno -> 2 // Return false and valueno = where it could be correctly inserted.
|
|
| locate substr in ordered dynamic array locateby() with fieldno and/or valueno arguments, searches fields if fieldno is 0, or values in a specific fieldno, or subvalues in a specific valueno. For more info, see locateby() without fieldno or valueno arguments.
var num;
if ("f1^f2^aaa]bbb]ccc^f4"_var.locateby("AL", "bb", num, 3)) ... // num -> 2 // return false and where it could be correctly inserted.
|
|
| locate substr using any delimiter.
if ("AB,EF,CD"_var.locateusing(",", "EF")) ... ok
|
|
| locate substr in dynamic array using any delimiter Search in a specific field, value or subvalue. num[out]: If found, the number where found, otherwise the maximum number of delimited fields + 1. return: True if found and False if not. This is similar to the main locate command but the delimiter char can be specified e.g. a comma or TM etc.
var num;
if ("f1^f2^f3c1,f3c2,f3c3^f4"_var.locateusing(",", "f3c2", num, 3)) ... ok // num -> 2 // Return true
|
|
| locatebyusing() supports all the locate features in a single function. |
Database Access
Use | Function | Description |
---|---|---|
|
| Establish a connection to a database. conninfo: The DB connection string parameters are merged from the following places in descending priority.
Setting environment variable EXO_DBTRACE=1 will cause tracing of DB interface including SQL commands. dbconn[out]: Becomes a reference or handle for future functions that require a connection argument. For all the various DB function calls, the dbconn or operative var can be either:
var dbconn = "exodus";
if (not dbconn.connect("dbname=exodus user=exodus password=somesillysecret")) ...;
// or
if (not connect()) ...
// or
if (not connect("exodus")) ...
|
|
| Attach filename(s) to a specific DB connection. Any following use of the given filename(s) without specifying a connection will be directed to the specified connection until process termination. It is not necessary to attach files before opening them but the act of opening them also attaches them. The files must exist in the specified connection. Attachments can changed by calling attach() or open() on a different connection or they can be removed by calling detach(). dbconn: The connection to which the filename(s) should be attached. Defaults to the default connection. filenames: FM separated list. return: False if any filename does not exist and cannot be opened on the given connection. All filenames that can be opened on the connection 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.
var dbconn = "exodus";
let filenames = "xo_clients^dict.xo_clients"_var;
if (dbconn.attach(filenames)) ... ok
// or
if (attach(filenames)) ... ok
|
| Remove files from the internal cache created by previous open() and attach() calls. filenames: FM separated list. | |
|
| Begin a DB transaction. return:
var dbconn = "exodus";
if (not dbconn.begintrans()) ...
// or
if (not begintrans()) ...
|
|
| Check if a DB transaction is in progress. return: True or False.
var dbconn = "exodus";
if (dbconn.statustrans()) ... ok
// or
if (statustrans()) ... ok
|
|
| Rollback a DB transaction. return:
var dbconn = "exodus";
if (dbconn.rollbacktrans()) ... ok
// or
if (rollbacktrans()) ... ok
|
|
| Commit a DB transaction. return:
var dbconn = "exodus";
if (dbconn.committrans()) ... ok
// or
if (committrans()) ... ok
|
|
| Execute an sql command. return:
var dbconn = "exodus";
if (dbconn.sqlexec("select 1")) ... ok
// or
if (sqlexec("select 1")) ... ok
|
|
| Execute an SQL command and capture the response. return:
response: Any rows and columns returned are separated by RM and FM respectively. The first row is the column names. It is *ecommended* that you do not use sql directly unless you must, perhaps to manage or configure a database.
var dbconn = "exodus";
let sqlcmd = "select 'xxx' as col1, 'yyy' as col2";
var response;
if (dbconn.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
|
| Close a DB connection Free process resources both locally and in the database server.
var dbconn = "exodus";
dbconn.disconnect();
// or
disconnect();
| |
| Close all DB connections Free process resources both locally and in the database server(s). All connections are closed automatically when a process terminates.
var dbconn = "exodus";
dbconn.disconnectall();
// or
disconnectall();
| |
|
| return: The last OS or DB error message.
var v1 = var::lasterror();
// or
var v2 = lasterror();
|
| Set the lasterror() message. | |
| Log the last OS or DB error message. Output: To stdlog Prefix the output with source if provided.
var::loglasterror("main:");
// or
loglasterror("main:");
|
Database Management
Use | Function | Description |
---|---|---|
|
| Create a named database on a particular connection. Optionally copies an existing database from the same connection return: True or False. See lasterror() for errors.
var dbconn = "exodus";
if (not dbdelete("xo_gendoc_testdb")) {}; // Cleanup first
if (dbconn.dbcreate("xo_gendoc_testdb")) ... ok
// or
if (dbcreate("xo_gendoc_testdb")) ...
|
|
| Create a named database as a copy of an existing database. return: True or False. See lasterror() for errors.
var dbconn = "exodus";
if (not dbdelete("xo_gendoc_testdb2")) {}; // Cleanup first
if (dbconn.dbcopy("xo_gendoc_testdb", "xo_gendoc_testdb2")) ... ok
// or
if (dbcopy("xo_gendoc_testdb", "xo_gendoc_testdb2")) ...
|
|
| Get a list of available databases. A list for a given connection or the default connection. return: An FM delimited list.
var dbconn = "exodus";
let v1 = dbconn.dblist();
// or
let v2 = dblist();
|
|
| Delete (drop) a named database. return: True or False. See lasterror() for errors.
var dbconn = "exodus";
if (dbconn.dbdelete("xo_gendoc_testdb2")) ... ok
// or
if (dbdelete("xo_gendoc_testdb2")) ...
|
|
| Create a named DB file. filenames ending with "_temp" only last until the connection is closed. return: True or False. See lasterror() for errors.
let filename = "xo_gendoc_temp", dbconn = "exodus";
if (dbconn.createfile(filename)) ... ok
// or
if (createfile(filename)) ...
|
|
| Rename a DB file. return: True or False. See lasterror() for errors.
let dbconn = "exodus", filename = "xo_gendoc_temp", new_filename = "xo_gendoc_temp2";
if (dbconn.renamefile(filename, new_filename)) ... ok
// or
if (renamefile(filename, new_filename)) ...
|
|
| Get a list of all files in a database. return: An FM separated list.
var dbconn = "exodus";
if (not dbconn.listfiles()) ...
// or
if (not listfiles()) ...
|
|
| Delete all records in a DB file. return: True or False. See lasterror() for errors.
let dbconn = "exodus", filename = "xo_gendoc_temp2";
if (not dbconn.clearfile(filename)) ...
// or
if (not clearfile(filename)) ...
|
|
| Delete a DB file. return: True or False. See lasterror() for errors.
let dbconn = "exodus", filename = "xo_gendoc_temp2";
if (dbconn.deletefile(filename)) ... ok
// or
if (deletefile(filename)) ...
|
|
| Get the approx number of records in a DB file. Might return -1 if not known. Not very accurate inside transactions. return: An approximate number.
let dbconn = "exodus", filename = "xo_clients";
var nrecs1 = dbconn.reccount(filename);
// or
var nrecs2 = reccount(filename);
|
|
| Call the DB maintenance function. For one file or all files. Ensure that reccount() function is reasonably accurate. Despite the name, this doesnt flush any index. return: True or False. See lasterror() for errors.
|
Database File I/O
Use | Function | Description |
---|---|---|
|
| Open a DB file. To a var which can be used in subsequent DB function calls to access a specific file using a specific connection. dbconn: If dbconn is *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. return: See lasterror().
var file, filename = "xo_clients";
if (not file.open(filename)) ...
// or
if (not open(filename to file)) ...
|
| Close a DB file. Does nothing currently since database file vars consume no resources
var file = "xo_clients";
file.close();
// or
close(file);
| |
|
| Create 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. return: False if the index cannot be created for any reason. See lasterror().
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)) ...
|
|
| List secondary indexes. In a database or for a DB file. return: An FM separated list.
var dbconn = "exodus";
if (dbconn.listindex()) ... ok // include "xo_clients__date_created"
// or
if (listindex()) ... ok
|
|
| Delete a secondary index. For a DB file and field name. return: False if the index cannot be deleted for any reason. See lasterror().
var file = "xo_clients", fieldname = "DATE_CREATED";
if (file.deleteindex(fieldname)) ... ok
// or
if (deleteindex(file, fieldname)) ...
|
|
| Place 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:
var file = "xo_clients", key = "1000";
if (file.lock(key)) ... ok
// or
if (lock(file, key)) ...
|
|
| Remove a DB lock. A lock placed by the lock function. return: True or False. See lasterror().
var file = "xo_clients", key = "1000";
if (file.unlock(key)) ... ok
// or
if (unlock(file, key)) ...
|
|
| Remove all DB locks. All locks placed by the lock function in the specified connection. return: True or False. See lasterror().
var dbconn = "exodus";
if (not dbconn.unlockall()) ...
// or
if (not unlockall(dbconn)) ...
|
| Write a record into a DB file. Given a unique primary key, either inserts a new record or updates an existing record. return: Nothing since writes always succeed. throw: VarDBException if the file does not exist. 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);
| |
|
| Read a record from a DB file. Given a unique primary key. file: A DB filename or a var opened to a DB file. key: The key of the record to be read. return: 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)) ...
|
|
| Delete a record from a DB file. Given a unique primary key. return: True or False.
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)) ...
|
|
| Insert a new record in a DB file. Given a unique primary key. return: True or False.
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)) ...
|
|
| Update an existing record in a DB file. Given a unique primary key. return: True or False.
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)) ...
|
|
| Update the key of an existing record in a DB file. Given two unique primary keys. return: True or False.
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.
|
|
| Read a field from a DB file record. Same as read() but only returns a specific field number from the record. fieldno: The field number to return from the DB record. return: A string var.
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)) ...
|
| Write a field to a DB file record. 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);
| |
| Write 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);
| |
|
| Read a DB record first looking in a memory cached "DB file". Same as "read() but first reads from a memory cache held per connection.
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
|
|
| Delete a record from a memory cached "DB file". The actual database file is NOT updated. return: False if the key doesnt exist
var file = "xo_clients", key = "XD001";
if (file.deletec(key)) ... ok
// or
if (deletec(file, key)) ...
|
| Clear the "DB file" memory cache. All cached 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.
let dbconn = "exodus";
dbconn.clearcache();
// or
clearcache(dbconn);
| |
|
| Read a field given filename, key and field number or name. 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 named columns, functions and multivalued data. strvar: 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: Which field of the record to return.
mode: If the record does not exist.
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 |
---|---|---|
|
| Create an active select list of DB keys. 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. return: True if any records are selected or false if none. throw: 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);
|
|
| Create an active select list from a string of DB keys. Similar to select() but creates the list directly from a var. keys: An FM separated list of keys or key^VM^valueno pairs. return: 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");
|
|
| Check if a select list is active. dbfile: A file or connection var used in a prior select, selectkeys or getlist function call. return: 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());
}
|
|
| Acquire and consume one key from an active select list. 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. dbfile: A file or connection var used in a prior select, selectkeys or getlist function call. key[out]: Returns the first (next) key present in an active select list or "" if no select list is active. return: True if a list was active and a key was acquired, false if not. |
|
| Acquire and consume one key and valueno pair from an active select list. 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. |
|
| Similar to readnext(key, valueno) but acquire the database record as well. record[out]: Returns the next database record from the select list assuming that the select list was created with the (R) option otherwise "" if not. key[out]: Returns the next database record key in the select list. valueno[out]: The multivalue number if the select list was ordered on multivalued database record fields or 1 if not. return: True if a list was active and a key was acquired, false 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"));
|
| Deactivate an active select list. dbfile: A file or connection var used in a prior select, selectkeys or getlist function call. return: 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
| |
|
| Save 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. return: 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
}
|
|
| 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. return: 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);
}
|
|
| 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. return: True if successful or false if the list name doesnt exist.
var dbconn = "";
if (dbconn.deletelist("mylist")) ... ok
// or
if (deletelist("mylist")) ...
|
OS Time/Date
Use | Function | Description |
---|---|---|
|
| Get the current date in internal format. Internal format is the number of whole days since pick epoch 1967-12-31 00:00:00 UTC. Dates prior to that are numbered negatively. return: A number. e.g. 20821 represents 2025-01-01 00:00:00 UTC for 24 hours.
let today1 = var::date();
// or
let today2 = date();
|
|
| Get the current time in internal format. Internal time is the number of whole seconds since the last midnight 00:00:00 (UTC). return: A number in the range 0 - 86399 since there are 24*60*60 seconds in a day. e.g. 43200 if time is 12:00:00
let now1 = var::time();
// or
let now2 = time();
|
|
| Get the current time in high resolution internal format. High resolution internal time is the number of fractional seconds since the last midnight 00:00:00 (UTC). return: 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();
|
|
| Get the current timestamp in internal format. Internal timestamp is the number of fractional days since pick epoch 1967-12-31 00:00:00 UTC. Negative for dates before. return: 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();
|
|
| Get the timestamp for a given date and time vardate: Internal date from date(), iconv("D") etc. ostime: Internal time from time(), ostime(), iconv("MT") etc.
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);
|
| Sleep/pause/wait milliseconds: How to long to sleep. Release the processor if not needed for a period of time or a delay is required.
var::ossleep(100); // sleep for 100ms
// or
ossleep(100);
| |
|
| Sleep/pause/wait up for a file system event file_dir_list: An FM delimited list of OS files and/or dirs to monitor. milliseconds: How long to wait. Any terminal input (e.g. a key press) will also terminate the wait. return: An FM array of event information is returned. See below. Multiple events may be captured and 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 dynamic array fields:
Possible event type codes:
|
OS File I/O
Use | Function | Description |
---|---|---|
|
| Open an OS file handle. Allow random read and write operations. Open for writing if possible, otherwise read-only. osfilevar[out]: Handle for subsequent osbread() and osbwrite() calls. osfilename: Path and name of an existing OS file. utf8: True (default) removes partial UTF-8 sequences from osbread() ends; false returns raw data. return: True if opened successfully, false if file doesn’t exist or isn’t accessible.
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
|
|
| Random write data to an OS file. At a specified position. strvar: Data to write. osfilevar: Handle from osopen() or a path/filename; creates file if offset is 0 and it’s new, fails if offset isn’t 0. offset: [in/out] Start position (0-based); updated to end of written data; -1 appends. return: True if write succeeds, false if file isn’t accessible, updateable, or creatable.
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
let text = "aaa=123\nbbb=456\n";
var offset = -1; /// -1 means append.
if (text.osbwrite(osfilename, offset)) ... ok // offset -> 16
// or
if (not osbwrite(text on osfilename, offset)) ...
|
|
| Random read data from an OS file From a specified position. strvar[out]: Data read. osfilevar: Handle from osopen() or a path/filename. offset: [in/out] Start position (0-based); updated to end of read data. length: Chars to read; with utf8=true (default), may return less to ensure complete UTF-8 code points. return: True if read succeeds, false if file doesn’t exist or isn’t accessible or offset >= file size.
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
|
| Use convenient << syntax to output anything to an osfile. osfile: An OS path and filename or an osfilevar opened by osopen(). The file will be appended, or created if it does not already exist. osfile can be "stdout" or "stderr" to simulate cout/cerr/clog.
let txtfile = "t_temp.txt";
if (not osremove(txtfile)) {} // Remove any existing file.
txtfile << txtfile << " " << 123.456789 << " " << 123 << std::endl;
let v1 = osread(txtfile); // "t_temp.txt 123.457 123\n"
All standard c++ io manipulators may be used e.g. std::setw, setfill etc.
let vout = "t_std_iomanip_overview.txt";
if (not osremove(vout)) {}
using namespace std;
vout << boolalpha << true << "\ttrue" << endl;
vout << noboolalpha << true << "\t1" << endl;
vout << showpoint << 42.0 << "\t42.0000" << endl;
vout << noshowpoint << 42.0 << "\t42" << endl;
vout << showpos << 42 << "\t+42" << endl;
vout << noshowpos << 42 << "\t42" << endl;
vout << skipws << " " << 42 << "\t 42" << endl;
vout << noskipws << " " << 42 << "\t 42" << endl;
vout << unitbuf << "a" << "\ta" << endl;
vout << nounitbuf << "b" << "\tb" << endl;
vout << setw(6) << 42 << "\t 42" << endl;
vout << left << setw(6) << 42 << "\t42 " << endl;
vout << right << setw(6) << 42 << "\t 42" << endl;
vout << internal << setw(6) << 42 << "\t 42" << endl;
vout << setfill('*') << setw(6) << 42 << "\t****42" << endl;
vout << showbase << hex << 255 << "\t0xff" << endl;
vout << noshowbase << 255 << "\tff" << endl;
vout << uppercase << 255 << "\tFF" << endl;
vout << nouppercase << 255 << "\tff" << endl;
vout << oct << 255 << "\t377" << endl;
vout << hex << 255 << "\tff" << endl;
vout << dec << 255 << "\t255" << endl;
vout << fixed << 42.1 << "\t42.100000" << endl;
vout << scientific << 42.1 << "\t4.210000e+01" << endl;
vout << hexfloat << 42.1 << "\t0x1.50ccccccccccdp+5" << endl;
vout << defaultfloat << 42.1 << "\t42.1" << endl;
vout << std::setprecision(3) << 42.1567 << "\t42.2" << endl;
vout << resetiosflags(ios::fixed) << 42.1567 << "\t42.2" << endl;
vout << setiosflags(ios::showpos) << 42 << "\t+42" << endl;
// Verify actual v. expected.
var act_v_exp = osread(vout);
act_v_exp.converter("\n\t", FM ^ VM); /// Text to dynamic array
act_v_exp = invertarray(act_v_exp); /// Columns <-> Rows
assert(act_v_exp.f(1) eq act_v_exp.f(2));
| |
| Close an osfilevar. Remove 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.
var osfilevar; if (osfilevar.osopen(ostempfile())) ... ok
osfilevar.osclose();
// or
osclose(osfilevar);
| |
|
| 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. return: True if successful or false if not possible for any reason. e.g. Path is not writeable, permissions etc
let text = &qquot;aaa = 123\nbbb = 456";
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
if (text.oswrite(osfilename)) ... ok
// or
if (oswrite(text on osfilename)) ... ok
|
|
| 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. return: 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);
|
|
| Rename 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. return: 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)) ...
|
|
| "Move" an OS file or dir. Within the OS file system. Attempt osrename first, then oscopy plus 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. return: 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)) ...
|
|
| Copy an OS file or directory. Including subdirs. 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. return: 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
|
|
| Remove/delete 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. return: True if successful or false if not possible for any reason. e.g. Target doesnt exist, path is not writeable, permissions etc. If osfilename is an osfilevar then it is automatically closed.
let osfilename = ostempdir() ^ "xo_gendoc_test.conf";
if (osfilename.osremove()) ... ok
// or
if (osremove(osfilename)) ...
|
OS Directories
Use | Function | Description |
---|---|---|
|
| 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:
return: 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");
|
|
| Get a list of OS files. See oslist() for info. |
|
| Get a list of OS dirs. See oslist() for info. |
|
| Get dir info about an OS file or dir. return: 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");
|
|
| Get dir info of an OS file. osfilename: Absolute or relative path and file name. return: 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");
|
|
| Get dir info of an OS dir. dirpath: Absolute or relative path and dir name. return: 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/");
|
|
| Create a new OS file system directory. Parent dirs wil be created if necessary. dirpath: Absolute or relative path and dir name. return: True if successful.
let osdirname = "xo_test/aaa";
if (osrmdir("xo_test/aaa")) {}; // Cleanup first
if (osdirname.osmkdir()) ... ok
// or
if (osmkdir(osdirname)) ...
|
|
| Change the current working dir. newpath: An absolute or relative dir path and name. return: 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.
|
|
| Get the current working dir path and name. return: The current working dir path and name. e.g. "/root/exodus/cli/src/xo_test/aaa"
var cwd1 = var().oscwd();
// or
var cwd2 = oscwd();
|
|
| Remove (deletes) an OS dir, eventifnotempty: If true any subdirs will also be removed/deleted recursively, otherwise the function will fail and return false. return: 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 |
---|---|---|
|
| Execute a shell command. command: An executable command to be interpreted by the default OS shell. return: 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
|
|
| Execute a shell command and capture its stdout. return: 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);
|
|
| Execute a shell command and provide its stdin. return: 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
|
|
| Run an OS program synchronously. Provide its standard input and capture its output, errors, and exit status. Shell features (e.g., pipes, redirects) are unsupported but can be invoked via an oscmd like "bash -c 'abc|yy $HOME'". oscmd: Executable and arguments; must exist in OS PATH. stdin_for_process: Optional; input data for the program’s standard input. stdout_from_process[out]: Standard output from the program. stderr_from_process[out]: Error/log output from the program. exit_status[out]: Program’s exit status: 0 (normal), -1 (timeout), else (error). timeout_secs: Optional; max runtime in seconds (default 0 = no timeout). return: True if program ran and exited with status 0 (success) or false if program failed to start, timed out, or exited with non-zero status. throw: Pipe creation failed, fork failed, poll failed.
var v_stdout, v_stderr, v_exit_status;
if (var::osprocess("grep xyz", "abc\nxyz 123\ndef", v_stdout, v_stderr, v_exit_status)) ... ok // v_stdout -> "xyz 123" // v_exit_status = 0
// or
if (osprocess("grep xyz", "abc\nxyz 123\ndef", v_stdout, v_stderr, v_exit_status)) ... ok
|
|
| Get the tmp dir path. return: A string e.g. "/tmp/"
let v1 = var::ostempdir();
// or
let v2 = ostempdir();
|
|
| Create a temporary file. return: The name of new temporary file e.g. "/tmp/~exoEcLj3C"
var temposfilename1 = var::ostempfile();
// or
var temposfilename2 = ostempfile();
|
|
| 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... return: 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"
|
| 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);
| |
|
| Get the current OS process id. return: A number e.g. 663237.
let pid1 = var::ospid(); /// e.g. 663237
// or
let pid2 = ospid();
|
|
| Get the current OS thread process id. return: A number e.g. 663237.
let tid1 = var::ostid(); /// e.g. 663237
// or
let tid2 = ostid();
|
|
| Get the exodus library version info. return: 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();
|
|
| Set 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
|
|
| Get the current thread's default locale. return: A locale codepage code string.
let v1 = var::getxlocale(); // "en_US.utf8"
// or
let v2 = getxlocale();
|
Output
Use | Function | Description |
---|---|---|
|
| Output to stdout with optional prefix. Append 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.
|
|
| Same as outputl() but doesnt append an NL char and is BUFFERED, not flushed. |
|
| Same as outputl() but appends a tab char instead of an NL char and is BUFFERED, not flushed. |
|
| 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.
|
|
| Same as logputl() but doesnt append an NL char. |
|
| 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.
|
|
| Same as errputl() but doesnt append an NL char and is BUFFERED not flushed. |
|
| Output to a given stream. Is BUFFERED not flushed. The raw string bytes are output. No character or byte conversion is performed. |
| Flush any and all buffered output to stdout and stdlog.
var().osflush();
// or
osflush();
|
Input
Use | Function | Description |
---|---|---|
|
| Read one line of input from stdin. return: 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();
|
|
| 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. return: ASCII or key code defined according to terminal protocol. return: "" 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();
|
|
| Check if is a terminal or a file/pipe. Can check stdin, stdout, stderr. in_out_err:
return: 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();
|
|
| Check 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. return: 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. |
|
| True if stdin is at end of file |
|
| Set 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. return: True if successful. |
| Install various interrupt handlers. Automatically called in program/thread initialisation by exodus_main.
| |
| Disable keyboard interrupt. Ctrl+C becomes inactive in terminal. |
Math/Boolean
Use | Function | Description |
---|---|---|
|
| Absolute value. let v1 = -12.34;
let v2 = v1.abs(); // 12.34
// or
let v3 = abs(v1);
|
|
| Power. let v1 = var(2).pwr(8); // 256
// or
let v2 = pwr(2, 8);
|
| Initialise the seed for rnd(). Allow 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);
| |
|
| Pseudo random number generator. return: A pseudo random integer between 0 and the provided maximum minus 1. Uses std::mt19937 and std::uniform_int_distribution<int>
let v1 = var(100).rnd(); /// Random 0 to 99
// or
let v2 = rnd(100);
|
|
| Power of e. let v1 = var(1).exp(); // 2.718281828459045
// or
let v2 = exp(1);
|
|
| Square root. let v1 = var(100).sqrt(); // 10
// or
let v2 = sqrt(100);
|
|
| Sine of degrees. let v1 = var(30).sin(); // 0.5
// or
let v2 = sin(30);
|
|
| Cosine of degrees. let v1 = var(60).cos(); // 0.5
// or
let v2 = cos(60);
|
|
| Tangent of degrees. let v1 = var(45).tan(); // 1
// or
let v2 = tan(45);
|
|
| Arctangent of degrees. let v1 = var(1).atan(); // 45
// or
let v2 = atan(1);
|
|
| Natural logarithm. return: Floating point var (double) let v1 = var(2.718281828459045).loge(); // 1
// or
let v2 = loge(2.718281828459045);
|
|
| Truncate decimals. Convert decimal to nearest integer towards zero. Remove decimal fraction. return: 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);
|
|
| Floor decimals. Convert decimal to nearest integer towards negative infinity. return: 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);
|
|
| Modulus function. Identical to C++ % operator only for positive numbers and modulus Negative denominators are considered as periodic with positive numbers Result is between [0, modulus) if modulus is positive Result is between (modulus, 0] if modulus is negative (symmetric) throw: 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
|
|
| Set 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. With the default precision, Exodus handles, without assistance, conversion to and from strings for positive and negative numbers between 0.0001 and 999'999'999'999.9999 (12 digits). newprecision: New precision between -307 and 308 inclusive. return: 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.
|
|
| Get current floating point precision. return: 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 |
---|---|---|
|
| oconv "D" Convert internal date to external format. Date output: Convert internal date format to human readable date or calendar info in text format. return: 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" ) ;
|
|
| iconv "D" Convert external date format to internal. Date input: Convert human readable date to internal date format. return: 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
|
|
| oconv "MT" Convert internal time to external format. Time output: Convert internal time format to human readable time e.g. "10:30:59". return: Human readable time or the original value unconverted if non-numeric. Conversion code (e.g. "MTHS") is "MT" ^ flags ... flags:
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"
|
|
| iconv "MT" Convert external time format to internal. Time input: Convert human readable time (e.g. "10:30:59") to internal time format. return: 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
|
|
| oconv "MD" Convert internal numbers to external format. Number output: Convert internal numbers to external text format after rounding and optional scaling. return: A string or, if the value is not numeric, then no conversion is performed and the original value is returned. conversion_code: (e.g. "MD20Z") is "MD" or "MC", 1st digit, 2nd digit, flags ...
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:
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"
|
|
| oconv "L" "R" "C" Justify text and numbers. 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"
|
|
| oconv "T" Justify and fold text. e.g. T#20 Useful when outputting to terminal devices where spaces are used for alignment. Split text into multiple fixed length lines by inserting spaces and TM chars. ASCII only.
let v1 = "Have a nice day";
let v2 = v1.oconv("T#10") ; // "Have a␣␣␣␣|nice day␣␣"_var
// or
let v3 = oconv(v1, "T#10") ; // "Have a␣␣␣␣|nice day␣␣"_var
|
|
| oconv "MR" Replace characters. 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
|
|
| oconv "HEX" Convert a string of chars to a string of pairs of hexadecimal digits. strvar: 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"
|
|
| iconv "HEX" Convert a string of pairs of hexadecimal digits to a string of chars. strvar: Must be a string of only hex digits 0-9, a-f or A-F. return: 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. |
|
| oconv "MX" Convert a number to hexadecimal string.
"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. return: 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).
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");
|
|
| iconv "MX" Convert a hexadecimal string to number. strvar: A string or dynamic array of up to 16 hex digits: 0-9, a-f, A-F. return: 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.
Hex "FFFF" "FFFF" "FFFF" "FFFF" (8 x "FF") -> -1. Hex "7FFF" "FFFF" "FFFF" "FFFF" -> The maximum positive integer: 9223372036854775805. Hex "8000" "0000" "0000" "0000" -> 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");
|
|
| oconv "MB" Convert a number to a binary string of "1"s and "0"s, 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");
|
|
| oconv "TX" Convert a dynamic array to text. Convert dynamic arrays to standard text format. Useful for using text editors on dynamic arrays.
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"
|
|
| iconv "TX" Convert text to a dynamic array. Convert standard text format to dynamic array. Reverse of oconv("TX") above. |
Contents:
Dimensioned Array Construction
Use | Function | Description |
---|---|---|
| Create an undimensioned array of vars. Pending actual dimensions by redim, read, osread or split.
dim d1;
| |
| Create a dimensioned array of vars. Specify a fixed number of columns and rows. All vars are unassigned.
dim d1(10);
dim d2(10, 3);
| |
| Copy a dimensioned array. Unassigned elements are copied as is.
dim d1 = {2, 4, 6, 8};
dim d2 = d1;
| |
| Save a dimensioned array created elsewhere. Use C++ "move" semantics.
dim d1 = "f1^f2^f3"_var.split();
| |
| Create a dimensioned array from a literal list. All elements must be the same type, var, string, double, int, etc. All end up as vars which are flexible.
dim d1 = {1, 2, 3, 4, 5};
dim d2 = {"A", "B", "C"};
| |
| Initialise all elements of an dimensioned array. To some single value. e.g. a var, "", 0 etc.
dim d1(10);
d1 = "";
| |
| Resize a dimensioned array. To a different number of rows and columns. Existing data will be retained. 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);
| |
| Swap two arrays. Either or both may be undimensioned.
dim d1(5);
dim d2(10);
d1.swap(d2);
|
Array Access
Use | Function | Description |
---|---|---|
| [row] Access and update dimensioned array elements. Two dimensioned arrays can be traversed, columnwise then rowwise, using one dimension array access.
dim d1 = {1, 2, 3, 4, 5};
d1[3] = "X";
let v1 = d1[3]; // "X"
| |
| [row, col] Access and update dimensioned array elements.
dim d1(10, 5);
d1 = "";
d1[3, 4] = "X";
let v1 = d1[3, 4]; // "X"
| |
|
| Get the number of rows in the dimensioned array return: A count. Can be zero, indicating an empty or undimensioned array.
dim d1(5,3);
let v1 = d1.rows(); // 5
|
|
| Get the number of columns in the dimensioned array return: A count. 0 if the array is undimensioned.
dim d1(5,3);
let v1 = d1.cols(); // 3
|
|
| Get a delimited string concatenating all elements of a dimensioned array. Unassigned elements on the end are omitted. delimiter: Default is FM. return: A string var.
dim d1 = {"f1", "f2", "f3"};
let v1 = d1.join(); // "f1^f2^f3"_var
|
Array Mutation
Use | Function | Description |
---|---|---|
| Create or update a dimensioned array using a string with delimiters. 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 ""
| |
| Sort a dimensioned array. The order of the elements is adjusted so that each element is <= the next. reverse: If true, then the order is reversed. The default is false.
dim d1 = "2,20,10,1"_var.split(",");
d1.sorter();
let v1 = d1.join(","); // "1,2,10,20"_var
| |
| Reverse a dimensioned array. The order of the elements is reversed.
dim d1 = "2,20,10,1"_var.split(",");
d1.reverser();
let v1 = d1.join(","); // "1,10,20,2"_var
| |
| Randomise a dimensioned array. The order of the elements is randomised.
dim d1 = "2,20,10,1"_var.split(",");
d1.randomizer();
let v1 = d1.join(","); // random
|
Array Conversion
Use | Function | Description |
---|---|---|
|
| Get a sorted copy of a dimensioned array. |
|
| Get a reversed copy of a dimensioned array; |
|
| Get a randomised copy of a dimensioned array. |
Array DB I/O
Use | Function | Description |
---|---|---|
| Write a DB file record created from a dimensioned array. Each element in the array becomes a separate field in the DB record. Redundant trailing FMs are omitted.
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);
| |
|
| Read a DB file record into a dimensioned array. Each field in the database record becomes a single element in the array. return: 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 |
---|---|---|
|
| Create an entire OS text file from a dimensioned 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. return: 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)) ...
|
|
| Read an entire OS text file into a dimensioned 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. return: 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)) ...
|
Contents:
Select Lists
Use | Function | Description |
---|---|---|
|
| 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. return: 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
|
|
| Create an active select list from a dynamic array of keys.
selectkeys("SB001^JB001^JB002"_var);
if (readnext(ID)) ... ok // ID -> "SB001"
|
|
| Check if a select list is active.
if (hasnext()) ... ok
|
|
| Get the next key from an active select list. key[out]: A string. Typically the key of a db file record. return: 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"
|
|
| 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. return: 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
|
|
| 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. return: 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());
|
| Get a reference to the currently active select list and suspend it. Allow another select list to be activated and used temporarily before the original select list is reactivated. Multiple levels of pushselect/popselect can be used. 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.
| |
| Re-activate a select list using a reference provided by pushselect(). cursor: A var created by the pushselect() function. See pushselect() for more info. | |
| Deactivate an active select list. If no select list is active then nothing is done.
clearselect();
| |
|
| Delete multiple DB records using an active select list. return: 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")) ...
}
|
|
| Delete a single DB 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)) ...
|
|
| Save the current active select list under a given name. Select lists are saved in the DB file "lists". They are accessible to any Exodus process and remain until specifically deleted. After saving, the list is no longer active and hasnext() will return false. return: True if an active select list was saved, false if there was no active select list.
selectkeys("SB001^SB002"_var);
if (not savelist("my_list")) ...
|
|
| Create an active select list using a saved select list of a given name. A saved list is obtained from the "lists" file and activated. The list remains in the lists file for multiple use. return: True if an active select list was successfully reactivated, otherwise false.
if (not getlist("my_list")) ...
|
|
| 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 |
---|---|---|
|
| Run an Exodus program/library. Creates a new instance of an Exodus program library function object and calls its main() function using a command-like syntax, similar to that of running an OS executable program, and passes its arguments through the COMMAND and OPTIONS variables. A performed program/library's main function should have no arguments otherwise they appear unassigned and a segfault or core dump may occur. The Exodus program class member variables of a performed or executed program/library are all, as might be expected, initially unassigned unless specifically initialised inline. Note that this is not the same as calling a program library function (using function call syntax and round brackets funcx()), where the program/library/function's member variables are initially unassigned but retain their state between calls. command_line: Used to initialise the COMMAND, SENTENCE and OPTIONS environment variables of the performed exodus program/library. Analogous to passing function arguments. The first word of command_line is used as the name of the program/library to be loaded and run. return: Whatever the program returns from main() or passes as an argument to stop(). If the program terminates abnormally then it will return "" and lasterror() will contain some error message. The return value may be ignored so there is no need so wrap perform statements in if clauses to avoid compiler warnings. throw: All the various runtime errors based on VarError e.g. VarUnassigned. environment: The following environment variables are initialised on entry to the main function of the program/library and are preserved untouched (actually restored) in the calling program.
Exodus program/library/functions 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. See library.h for more info. |
|
| Run an exodus program/library. 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. |
| Close the current program and perform another one. Similar to perform() except that the current program closes first and all environment variables carry forward unchanged. | |
|
| Check if a lib exists. Can be checked before perform/execute to avoid errors. Currently it does not check if the library is actually loadable. return: osfile info. |
Program Termination
Use | Function | Description |
---|---|---|
| Stop the current exodus program/library normally. Either return to the performing or executing parent exodus program/library, or exit to the OS if none. result: Optional. It will be used as the return value of a parent program's perform() or execute() function, or if none, and therefore returning to the OS, it will be output to stdout if non-numeric or, if numeric, used as the exit status. | |
| Abort the current exodus program/library. Similar to stop but if exiting to the OS then the default exit status is 1. message: Optional. If exiting to the OS then it will be output to stderr or, if numeric, used as the exit status. | |
| Abort the current exodus program/library. Similar to abort but if exiting to the OS then the default exit status is 2. |
DB File Dictionaries
Use | Function | Description |
---|---|---|
|
| Get DB record field values given field name only. Use a dictionary file that contains info sufficient to either extract or calculate the required value.
|
|
| Get DB record field values given name and data. Same as the one argument version of calculate() but RECORD/ID/MV are provided as arguments instead of being hard coded. |
|
| Read DB field using field number or name.
filename: The file to read. key: The key of the record to read. fieldno_or_name: The field to return.
mode: If the record does not exist.
MV: Environment variable. Will be used to select a particular value if not zero, or all values if zero. |
I/O Conversion
Use | Function | Description |
---|---|---|
|
| iconv/oconv "[...]" ExoProgram's iconv/oconv functions have access to ExoProgram's environment variables like BASEFMT, DATEFMT and TZ and 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] |
|
|
Ioconv Date/Time
Use | Function | Description |
---|---|---|
|
| iconv/oconv "[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). return: [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. return: [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]");'.
DATEFMT = "D/E";
let v1 = iconv("JAN 9 2025", "D");
assert(oconv(v1, "[DATE]" ) == " 9/ 1/2025"); // "D/EZ" or "[DATE,D]" equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
assert(oconv(v1, "[DATE,4]" ) == " 9/ 1/2025"); // "D4Z" equivalent assuming D/E in DATEFMT (replace leading zeros with spaces)
assert(oconv(v1, "[DATE,*4]") == "9/1/2025"); // "D4ZZ" equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)
assert(oconv(v1, "[DATE,*]" ) == "9/1/2025"); // "DZZ" equivalent assuming D/E in DATEFMT (trim leading zeros and spaces)
|
|
| iconv/oconv "[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" return: 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.
var v1 = iconv("1,234.5678USD", "[NUMBER]"); // "1234.57USD" // Comma removed
|
|
| Parse amount+currency code string. Split amount+currency code/unit string into number and currency code/unit. var: "123.45USD" return: e.g. "123.45" unitx[out]: e.g. "USD" |
|
|
Time/Date Utilities
Use | Function | Description |
---|---|---|
|
| Get text of date and time. In users time zone e.g. "2MAR2025 11:52AM" Offset from UTC by TZ seconds. |
| Get current user, server and UTC dates and times. 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. | |
|
| Get text of elapsed time. Since environment variable TIMESTAMP. TIMESTAMP is initialised with ostimestamp() at program/thread startup. TIMESTAMP can be updated using ostimestamp() as and when desired.
var v1 = elapsedtimetext(); // e.g. "< 1ms"
|
|
| Get text of elapsed time. Between two given timestamps Warning: Use ostimestamp() not ostime(). The first is in days and the second is in seconds.
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 |
---|---|---|
| Output a message to stdout and optionally request input. If input is requested but stdin is not a terminal then set the response to "" and continue. options: R = Response requested. C upper case response.
var response;
// call note("Enter something", "RC", response);
| |
| Output a message to stdout.
call note("Hello world.");
| |
|
| Input user selection from a list of options. If stdin is not a terminal, set the response to "" and continue. return: The chosen option (value not number) or "" if the user cancelled. |
|
| Input user selection from a list of options. If stdin is not a terminal set the response to the default value, or "" if none, and continue. defaultreply: A default option if the user presses Enter. reply[out]: The option number that the user chose or "" if they cancelled. return: The chosen option (value not number) or "" if the user cancelled. |
|
| Check for user pause or cancel. 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. return:
|
|
| Get a string to control terminal operation. return: A string to be output to the terminal in order to accomplish the desired operation. The terminal protocol is xterminal. code:
|
|
| Get a terminal cursor positioning string. return: 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. |
|
| 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. x and y are 1 based, not 0 based. 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:
var cursor;
if (isterminal() and not getcursor(cursor)) ... // cursor becomes something like "1^20^0.012345"_var
|
|
| 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
|
| 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 |
---|---|---|
|
| Dynamic array fields become values and vice versa return: 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
|
| Sort parallel fields of multivalues of dynamic arrays fns: VM separated list of field numbers to sort in parallel based on the first field number order:
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 |
---|---|---|
|
| |
|
| |
|
| |
|
|