Here you find the documentation of the TeaScript Core Library which is integrated TeaScript and usable from within scripts.
Core Library Documentation
Hence the API is not yet finalized, the documentation is provided in a very simplified form. During time (and API finalization) the documentation will be enriched as well.
HINT: in interactive shell use command ':ls vars' for get a complete list of all present toplevel
variables and functions.
Or use ':search str' for search any variable and function containing 'str'.
Variable Name : Type --> docu
-------------------------------------------------------------------------------------------
_version_major : i64 --> major version of TeaScript
_version_minor : i64 --> minor version of TeaScript
_version_patch : i64 --> patch version of TeaScript
_version_combined_number: i64 --> combined version number for easily compare versions.
_version_build_date_time: String --> build date and time as string
_api_version : i64 --> version of Core Library API.
features : Tuple --> with elements format, color, toml: Bool, and json: i64
indicating whether the Library/Host Application was compiled with the features.
element json_adapter: String indicating the used JsonAdapter.
_init_core_stamp : f64 --> time stamp in fractional seconds from an unspecified time point during program start.
_core_config : i64 --> combined enum teascript::config::eConfig value used for boostrap the CoreLibrary.
_exit_success : i64 --> exit code for indicating success (used especially for exit/_exit)
_exit_failure : i64 --> exit code for indicating failure (used especially for exit/_exit)
void : NaV (Not a Value) --> Convenience for can write 'return void' if function shall return nothing.
PI : f64 --> The constant number PI
Func Name : Signature --> docu
-------------------------------------------------------------------------------------------
_out : void ( String ) --> prints param1 (String) to stdout
_err : void ( String ) --> prints param1 (String) to stderr
print : void ( Any ) --> prints param to stdout, will do to-string conversion of the parameter.
println : void ( Any ) --> prints param + line feed to stdout, will do to-string conversion of the parameter.
readline : String ( void ) --> read line from stdin (and blocks until line finished),
returns the read line without line feed.
_exit : void ( Any ) --> exits the script (with stack unwinding/scope cleanup) with param1 as return value.
(this function never returns!)
_strtonum : i64|Bool ( String ) --> converts a String to i64. Returns Bool(false) on error.
This works only with real String parameters. alternative for '+str'.
_strtonumex : i64|u8|u64|f64|Bool (String) --> converts a String to i64,u8,u64 or f64, Bool(false) on error.
This works only with real String objects.
_numtostr : String ( i64 ) --> converts a i64 to String. this works only with real i64 parameters.
Alternative for 'num % ""'
_f64toi64 : i64 (f64) --> converts a f64 to i64. same effect as trunc() but yields a i64.
to_string : String (val: Any) --> converts val to string (note: if val is an integer _numtostr is an alternative)
to_number : i64|u8|u64|f64|Bool (Any) --> converts val to a Number. returns Bool(false) on error.
(note: if val is a String _strtonum / _strtonumex is an alternative)
_eval : Any ( String ) --> parses and evaluates the string as TeaScript code and returns its result.
eval_file : Any ( String ) --> parses and evaluates the content of the file and returns its result.
All defined functions and variables in the top level scope will stay available.
fail : void ( void ) --> exits the script (with stack unwinding/scope cleanup) with
error_code _exit_failure (this function never returns!)
fail_with_error : void ( i64 ) --> exits the script (with stack unwinding/scope cleanup) with the i64 error_code.
(this function never returns!)
fail_with_message : void ( String, i64 ) --> prints String to stderr, exits the script (with stack unwinding/scope cleanup)
with the i64 error_code. (this function never returns!)
clock : f64 ( void ) --> gets the local wall clock time of the current day in (fractional) seconds as f64.
clock_utc : f64 ( void ) --> gets the UTC time of the current day in (fractional) seconds as f64.
(note: This UTC time is with leap seconds!)
_timestamp : f64 ( void ) --> gets the elapsed time in (fractional) seconds as f64 from an unspecified
time point during program start. Time is monotonic increasing.
sleep : void ( i64 ) --> sleeps (at least) for given amount of seconds.
random : i64 ( i64, i64 ) --> creates a random number in between [start,end]. start, end must be >= 0 and <= UINT_MAX.
min : Any ( Any, Any ) --> returns the minimum of a and b
max : Any ( Any, Any ) --> returns the maximum of a and b
clamp : Any ( val: Any, low: Any, high: Any ) --> returns low if val is less than low, high if val is greater
than high, otherwise val. garbage in, garbage out.
swap : Any ( Any, Any ) --> swaps the values of a and b (a and b are passed via shared assign)
abs : Number ( Number ) --> returns the absolute value of n (as same type as n). n must be a Number.
trunc : f64 ( Number ) --> rounds the given Number towards zero as f64.
e.g. 1.9 will yield 1.0, -2.9 will yield -2.0.
floor : f64 ( Number ) --> rounds down the given Number to next smaller integer as f64.
e.g. 1.9 will yield 1.0, -2.1 will yield -3.0
ceil : f64 ( Number ) --> rounds up the given Number to next greater integer as f64.
e.g. 1.1 will yield 2.0, -1.9 will yield -1.0
round : f64 ( Number ) --> rounds up or down the given Number to nearest integer as f64.
e.g. 1.1 will yield 1.0, 1.6 as well as 1.5 will yield 2.0
pow : f64 ( Any, i64 ) --> computes power of input with integer exponent. if exp is a float it will get truncated.
returns a f64. (will do to-number conversion on input)
sqrt : f64 ( Any ) --> computes the square root of given input (will do to-number conversion on input).
timevals : Bool ( t: f64, HH: i64, MM: i64, S: i64, ms: i64 ) --> computes the hour, minute, second
and (optionally) millisecond part of given time in seconds (e.g. from clock())
note: hours can be greater than 23/24, it will not be cut at day boundary!
timetostr : Bool|String ( t, with_ms: Bool ) --> builds a 24 hour wall clock string with the
format HH:MM:SS.mmm (milliseconds are optional)
note: if t is greater than 24 hours it will not be cut.
rolldice : i64 ( eyes: i64 ) --> randomly rolls the dice and returns the result.
inc : Number ( Number (in/out), step: Number ) --> increments given Number by step (default 1)
dec : Number ( Number (in/out), step: Number ) --> decrements given Number by step (default 1)
_seq : Sequence (start, end, step: i64 ) --> creates an IntegerSequence of [start,end] with given step.
If end is smaller start, step must be negative.
A sequence starts at start and the next value is the result
of current + step. If end cannot be reached by step exactly
the value remains at the last current, e.g, _seq( 1, 10, 2 )
will be 1, 3, 5, 7, 9.
Sequences can be used in forall loops.
=== Tuple helper functions ===
_tuple_create : Tuple ( ... ) --> creates a tuple from the passed parameters.
parameter count is variable and type Any.
_tuple_named_create : Tuple ( ... ) --> creates a named Tuple from the given parameters.
The parameter must be of a 2 element sized Tuple whereby the first element
must be of type String and the second element can be Any.
example: _tuple_named_create( ("name", "John"), ("age", 31) )
_tuple_size : i64 ( Tuple ) --> returns the element count of the Tuple
_tuple_same_types : Bool ( Tuple, Tuple ) --> checks whether the 2 tuples have the same types in exactly the same order
(and with same names).
_tuple_val : Any ( Tuple, i64 ) --> returns the value at given index.
_tuple_named_val : Any ( Tuple, String ) --> returns the value with given name (or throws).
_tuple_set : void ( Tuple, i64, Any ) --> sets the value at given index or throws if index not exist.
_tuple_named_set : void ( Tuple, String, Any ) --> set the value with given name (or throws).
_tuple_append : void ( Tuple, Any ) --> appends new value to the end as new element.
_tuple_named_append : Bool ( Tuple, String, Any ) --> appends new value with given name to the end as new element
if the name not exist yet.
_tuple_insert : void ( Tuple, i64, Any ) --> inserts new value at given index.
_tuple_named_insert : void ( Tuple, i64, String, Any ) --> inserts a value with given name at given index.
_tuple_remove : Bool ( Tuple, i64 ) --> removes element at given index, returns whether an element has been removed.
_tuple_named_remove : Bool ( Tuple, String ) --> removes element with given name, returns whether an element has been removed.
_tuple_index_of : i64 ( Tuple, String ) --> returns the index of the element with given name or -1
_tuple_name_of : String ( Tuple, i64 ) --> returns the name of the element with given idx (or throws)
_tuple_swap : void ( Tuple, i64, i64 ) --> swaps elements of given indices
tuple_print : void ( Tuple, String, i64 ) --> prints (recursively) all (named) elements, for debugging
(String param is the "root" name, last param is for max nesting level)
=== "minimalistic string support" ===
_strlen : i64 ( String ) --> returns the length of the string in bytes (excluding the ending 0).
_strglyphs : i64 ( String ) --> returns the utf-8 (Unicode) glyph count of the string (excluding the ending 0).
_strglyphtobytepos : i64 ( String, i64 ) --> returns the byte position of the given glyph in given string, or -1 if out of range.
_strat : String ( String, i64 ) --> returns a substring of one complete UTF-8 code point where position points into.
_strat : String ( String, i64 ) --> returns a substring of one character at given position.
empty string if out of range.
_substr : String ( String, from: i64, count: i64 ) --> returns a substring [from, from+count).
count -1 means until end of string. returns empty string on invalid arguments.
_strfind : i64 ( String, substring: String, offset: i64 ) --> searches for substring from offset and
returns found pos of first occurrence. -1 if not found.
_strfindreverse : i64 ( String, substring: String, offset: i64 ) --> searches for substring from behind from offset and
returns found pos of first occurrence. -1 if not found.
_strreplacepos : Bool ( str: String, start: i64, count: i64, new: String ) --> replaces the section [start, start+count)
in str with new. returns false on error, e.g. start is out of range.
strreplacefirst : Bool ( str: String, what: String, new: String, offset: i64 := 0 ) --> replaces first occurrence of what
with new starting from offset. returns true if a replacement happen.
strreplacelast : Bool ( str: String, what: String, new: String, offset: i64 := 0 ) --> replaces last occurrence of what
with new starting from offset. returns true if a replacement happen.
strtrim : Bool ( str: String, set: String, leading: Bool, trailing: Bool ) --> trims the string if it starts or ends
with characters in given set.
strsplit : Tuple (str: String, sep: String, skip_empty : Bool := false ) --> splits the given string at every
occurring separator and returns a tuple wth the elements.
strjoin : String ( Tuple, sep: String, add_leading: Bool := false, add_trailing: Bool := false )
--> joins all elements of a tuple to a string with given separator.
_strfromascii : String|Bool ( char: Number ) --> returns a String build from the ascii char.
For invalid chars (>127) Bool(false) will be returned.
utf8_begin : UTF8_Iterator ( String ) --> creates an utf-8 iterator for the given string and
sets .cur to first utf-8 glyph.
utf8_end : Bool ( UTF8_Iterator ) --> returns whether the given utf-8 iterator is at end already.
utf8_next : UTF8_Iterator ( UTF8_Iterator ) --> sets the utf-8 iterator (.cur) to next utf-8 glyph or end of string.
=== "minimalistic (text) file io support" ===
NOTE: text files must be UTF-8 encoded. Pathes can be relative to "cwd" or absolute.
cwd : String ( void ) --> returns the current working directory as String
change_cwd : Bool ( String ) --> changes the current working dir
tempdir : String ( void ) --> returns configured temp directory as String
path_exists : Bool ( String ) --> returns whether path in String exists as directory or file.
file_exists : Bool ( String ) --> returns whether the given file exists.
file_size : i64 ( String ) --> returns file size in bytes. -1 on error / file not exists / is not a file.
last_modified : String ( String ) --> returns the last modified time as String for the given path or empty string
if not exists/error.
create_dir : Bool ( String, Bool ) --> creates directories for path in String. Bool == true means recursively.
path_delete : Bool ( String ) --> deletes(!) file or (empty) directory.
file_copy : Bool ( file: String, dest_dir: String, overwrite: Bool ) --> copies file to dest_dir if not exist
or overwrite is true.
file_copy_newer : Bool ( file: String, dest_dir: String ) --> copies file to dest_dir if not exist
or file is newer as the file in dest_dir.
readtextfile : String|Bool ( String ) --> reads the content of an UTF-8 text file and returns it in a String.
An optional BOM is removed.
writetextfile : Bool ( file: String, str: String, overwrite: Bool, bom: Bool ) --> writes the content of String to
text file. An optional UTF-8 BOM can be written (last Bool param).
overwrite indicates if a prior existing file shall be overwritten (old content destroyed!)
readfile : Buffer|Bool ( String ) --> reads the binary content of the file into a buffer. returns Bool(false) on error.
writefile : Bool ( file: String, content: Buffer, overwrite: Bool ) --> writes the content of the Buffer to the file.
overwrite indicates if a prior existing file shall be overwritten (old content destroyed!)
readdirfirst : Tuple ( String ) --> returns the first direntry of given path (see direntry for details)
readdirnext : Tuple ( Tuple ) --> returns the next direntry of given direntry (see direntry for details)
=== the direntry tuple ===
On Error or if directory is empty or if there are no more entries to iterate over the tuple has the following elements:
valid : Bool --> here false always.
error : i64 --> if greater 0 it is the reported error code from std::filesystem / the OS.
path : String --> the path which was investigated / tried to investigate.
In all other states the tuple has the following elements:
valid : Bool --> here true always.
name : String --> the name of the entry.
size : i64 --> the file size (for directories always 0)
last_modified : String --> last modified date/time as String with format "%F %T" (perfectly sortable)
is_file : Bool --> true if entry is file, false otherwise.
is_dir : Bool --> true if entry is directory, false otherwise.
path : String --> the absolute and canonical path of the entry.
_handle : Passthrough --> instance of std::filesystem::directory_iterator as Passthrough value.
=== JSON Support ===
readjsonstring : Any ( String ) --> creates a corresponding object from the given JSON formatted string.
Returns a TypeInfo on error (This will be replaced with an Error type once it exists).
readjsonfile : Any ( String ) --> creates a corresponding object from the given JSON formatted file.
Returns a TypeInfo on error (This will be replaced with an Error type once it exists).
writejsonstring : String ( Any ) --> creates a JSON formatted string from the object (or false on error).
writejsonfile : Bool ( Any ) --> writea a JSON formatted file from the object. returns true on success.
json_is_object : Bool ( Any ) --> checks if given parameter is an Json compatible object.
json_is_array : Bool ( Any ) --> checks if given parameter is an Json compatible array.
json_object_size : i64 ( Tuple ) --> returns the element count of the object.
json_array_size : i64 ( Tuple ) --> returns the element count of the array.
json_make_object : Tuple ( ... ) --> creates a compatible Json object from the passed parameters.
json_make_array : Tuple ( ... ) --> creates a compatible Json array from the passed parameters.
parameter count is variable and type Any.
json_array_empty : Bool ( Tuple ) --> checks if given Tuple is an empty Json array.
json_array_append : void ( Tuple, Any ) --> appends value to Json comaptible array
(the Tuple must be compatible, e.g., json_is_array returned true!)
json_array_insert : Bool ( Tuple, I64, Any ) --> inserts value at idx to Json comaptible array
(the Tuple must be compatible, e.g., json_is_array returned true!)
json_array_remove : Bool ( Tuple, I64 ) --> removes value at idx from Json comaptible array
(the Tuple must be compatible, e.g., json_is_array returned true!)
=== TOML Support ===
readtomlstring : Tuple ( String ) --> creates a named tuple from the given TOML formatted string (or false on error).
readtomlfile : Tuple ( String ) --> creates a named tuple from the given TOML formatted file (or false on error).
writetomlstring : String ( Tuple ) --> creates a TOML formatted string from the named tuple (or false on error).
writetomlfile : Bool ( Tuple ) --> writea a TOML formatted file from the named tuple. returns true on success.
toml_is_table : Bool ( Any ) --> checks if given parameter is an Toml compatible table.
toml_is_array : Bool ( Any ) --> checks if given parameter is an Toml compatible array.
toml_table_size : i64 ( Tuple ) --> returns the element count of the table.
toml_array_size : i64 ( Tuple ) --> returns the element count of the array.
toml_make_table : Tuple ( ... ) --> creates a compatible toml table from the passed parameters.
toml_make_array : Tuple ( ... ) --> creates a compatible toml array from the passed parameters.
parameter count is variable and type Any.
toml_array_empty : Bool ( Tuple ) --> checks if given Tuple is an empty Toml array.
toml_array_append : void ( Tuple, Any ) --> appends value to Toml comaptible array
(the Tuple must be compatible, e.g., toml_is_array returned true!)
toml_array_insert : Bool ( Tuple, I64, Any ) --> inserts value at idx to Toml comaptible array
(the Tuple must be compatible, e.g., toml_is_array returned true!)
toml_array_remove : Bool ( Tuple, I64 ) --> removes value at idx from Toml comaptible array
(the Tuple must be compatible, e.g., toml_is_array returned true!)
=== Color Output Support ===
make_rgb : i64 (r: i64, g: i64, b: i64) --> makes a 32 bit rgb color (garbage in, garbage out)
cprint : void (i64, String) --> prints the text in the given rgb color (only available with libfmt)
cprintln : void (i64, String) --> same as cprint but adds a new line to the end.
=== Format String Support ===
format : String ( format: String, ... ) --> formats the string with libfmt the same way as known from C++.
=== Buffer Support ===
General information:
Buffers are represented as contiguous memory and can be accessed and modified bytewise at byte boundaries (1 byte = 8 bit).
It is not possible to share assign from a single byte of a buffer.
The Subscript operator can be used for access and modify an existing byte.
Buffers will not grow behind its original capacity automatically (use _buf_resize), but its size will grow up to its capacity.
Memory will be freed automatically if last reference goes out of scope or being undef'ed.
Because TeaScript has only one signed integral type, I64, all setter and getter for signed types are operating with I64.
Because TeaScript has only U8 and U64 as unsigned integral types, all getter and setter using a bigger type than U8
are operating with U64 as type.
All getters and setters are operating in host byte order.
_buf : Buffer ( size: Number ) --> creates an empty Buffer (size == 0) with capacity 'size'.
_buf_size : U64 ( Buffer ) --> returns the actual amount of used/filled bytes in the buffer.
_buf_capacity : U64 ( Buffer ) --> returns the amount of allocated memory in bytes for the buffer.
buf_zero : void ( Buffer ) --> fills the complete capacity of the buffer with zeroes. post: size == capacity
_buf_fill : Bool ( Buffer, pos: Number, count: Number, val: U8 ) --> fills the buffer from pos up to pos + count with val.
_buf_fill32 : Bool ( Buffer, pos: Number, count: Number, val: U64 ) --> fills the buffer from pos up to pos + count
with val as u32. The passed range must be dividable by 4 (sizeof u32).
_buf_resize : Bool ( Buffer, size: Number ) --> resizes the buffer (shrink or grow). new values are added as zero.
see _buf_fill also.
_buf_copy : Bool ( dst: Buffer, dst_off: Number, src: Buffer, src_off: Number, len: Number )
--> copies src buffer into dst buffer.
_buf_at : U8 ( Buffer, pos: Number ) --> returns byte at given position, throws on out of range.
_buf_get_u8 : U8|Bool ( Buffer, pos: Number ) --> gets an U8 from buffer at given position, returns Bool(false) on failure.
_buf_get_u16 : U64|Bool ( Buffer, pos: Number ) --> gets an U16 as U64 from buffer at given position, returns Bool(false) on failure.
_buf_get_u32 : U64|Bool ( Buffer, pos: Number ) --> gets an U32 as U64 from buffer at given position, returns Bool(false) on failure.
_buf_get_u64 : U64|Bool ( Buffer, pos: Number ) --> gets an U64 from buffer at given position, returns Bool(false) on failure.
_buf_get_i8 : I64|Bool ( Buffer, pos: Number ) --> gets an I8 as I64 from buffer at given position, returns Bool(false) on failure.
_buf_get_i16 : I64|Bool ( Buffer, pos: Number ) --> gets an I16 as I64 from buffer at given position, returns Bool(false) on failure.
_buf_get_i32 : I64|Bool ( Buffer, pos: Number ) --> gets an I32 as I64 from buffer at given position, returns Bool(false) on failure.
_buf_get_i64 : I64|Bool ( Buffer, pos: Number ) --> gets an I64 from buffer at given position, returns Bool(false) on failure.
For all setters apply: if pos == size the buffer will grow if the capacity is big enough.
_buf_set_u8 : Bool ( Buffer, pos: Number, val: U8 ) --> sets val as U8 in buffer at given position, returns true on success.
_buf_set_u16 : Bool ( Buffer, pos: Number, val: U64 ) --> sets val as U16 in buffer at given position, returns true on success.
_buf_set_u32 : Bool ( Buffer, pos: Number, val: U64 ) --> sets val as U32 in buffer at given position, returns true on success.
_buf_set_u64 : Bool ( Buffer, pos: Number, val: U64 ) --> sets val as U64 in buffer at given position, returns true on success.
_buf_set_i8 : Bool ( Buffer, pos: Number, val: I64 ) --> sets val as I8 in buffer at given position, returns true on success.
_buf_set_i16 : Bool ( Buffer, pos: Number, val: I64 ) --> sets val as I16 in buffer at given position, returns true on success.
_buf_set_i32 : Bool ( Buffer, pos: Number, val: I64 ) --> sets val as I32 in buffer at given position, returns true on success.
_buf_set_i64 : Bool ( Buffer, pos: Number, val: I64 ) --> sets val as I64 in buffer at given position, returns true on success.
_buf_set_string : Bool ( Buffer, pos: Number, val: String ) --> writes the String (_without_ trailing 0!) val into the buffer
at given position, returns true on success.
_buf_get_string : String|Bool ( Buffer, pos: Number, len: Number ) --> gets a String from buffer at given position,
must be valid UTF-8, returns Bool(false) on failure.
_buf_get_ascii : String|Bool ( Buffer, pos: Number, len: Number ) --> gets a String from buffer at given position,
all values must be in range [0,127], returns Bool(false) on failure.
Source Code of the Core Library
This is a snapshot of the source code of the TeaScript Core Library part which is written in TeaScript. The other part is written in C++.
Have a look in CoreLibrary.hpp for obtain the complete and up-to-date code.
// convenience for can write 'return void' if function shall return nothing
const void := () // void has value NaV (Not A Value)
// constant number PI
const PI := 3.14159265358979323846
// exits the script (with stack unwinding/scope cleanup) with given code, will do to number conversion of code.
func exit( code )
{
_exit( +code )
}
// exits the script (with stack unwinding/scope cleanup) with code EXIT_FAILURE
func fail()
{
fail_with_error( _exit_failure )
}
// exits the script (with stack unwinding/scope cleanup) with error_code
func fail_with_error( error_code )
{
_exit( error_code )
}
// converts val to string (note: if val is an integer _numtostr is an alternative)
func to_string( val )
{
val % ""
}
// converts val to a Number. returns Bool(false) on error. (note: if val is a String _strtonum / _strtonumex is an alternative)
func to_number( val )
{
if( val is String ) {
_strtonumex( val ) // this can convert i64 and f64
} else {
+val //TODO: error handling!
}
}
// converts val to f64. val must be a number already! returns Bool(false) on error.
// example use case: to_f64( to_number( some_var ) ) // ensures some_var is converted to f64
// NOTE: this function is only provisionally and will be replaced by a cast later!
func to_f64( val )
{
if( val is Number ) { val + 0.0 } else { false }
}
// convenience function. ensures given Number is used as i64. returns Bool(false) on error.
// example use case: to_i64( to_number( some_var ) ) // ensures some_var is converted to i64
// NOTE: this function is only provisionally and will be replaced by a cast later!
func to_i64( val )
{
if( val is Number ) {
val as i64
} else {
false
}
}
// returns the minimum of a and b
func min( a, b )
{
if( a < b ) { a } else { b }
}
// returns the maximum of a and b
func max( a, b )
{
if( b < a ) { a } else { b }
}
// returns low if val is less than low, high if val is greater than high, otherwise val. garbage in, garbage out.
func clamp( val, low, high )
{
min( max( val, low ), high )
}
// swaps the values of a and b (a and b are passed via shared assign)
func swap( a @=, b @= )
{
if( not (a @@ b) ) { // only if b is not shared by a
const tmp := a
a := b
b := tmp
}
void
}
// convenience for _strfind with default offset
func strfind( str, what, offset := 0 )
{
_strfind( str, what, offset )
}
// returns the absolute value of n (as same type as n). n must be a Number.
func abs( n )
{
if( n < 0 ) { -n } else { n }
}
// rounds up or down the given Number to nearest integer as f64. e.g. 1.1 will yield 1.0, 1.6 as well as 1.5 will yield 2.0
func round( n )
{
const num := (n + 0.0)
0.0 + _f64toi64( num + if( num < 0 ) { -0.5 } else { 0.5 } )
}
// make_rgb : i64 (r: i64, g: i64, b: i64) --> makes a 32 bit rgb color (garbage in, garbage out)
// (same level as cprint)
func make_rgb( r, g, b )
{
r bit_lsh 16 bit_or g bit_lsh 8 bit_or b
}
// increments by given step
func inc( n @=, step := 1 )
{
n := n + step
}
// decrements by given step
func dec( n @=, step := 1 )
{
n := n - step
}
// fills the complete capacity of the buffer with zeroes (convenience). post: size == capacity
func buf_zero( buf @= )
{
_buf_fill( buf, 0, -1, 0u8 )
}
// prints s to stdout, will do to string conversion of s
func print( s )
{
_out( s % "" )
}
// prints s + line feed to stdout, will do to string conversion of s
func println( s )
{
_out( s % "\n" )
}
// prints s + line feed to stderr, will do to string conversion of s
func print_error( s )
{
//TODO: add log to common logfile
_err( s % "\n" )
}
// prints error_str to stderr, exits the script (with stack unwinding/scope cleanup) with error_code
func fail_with_message( error_str, error_code := _exit_failure )
{
print_error( error_str )
fail_with_error( error_code )
}
func file_exists( file )
{
file_size( file ) >= 0
}
func readtomlfile( file )
{
const content := readtextfile( file )
if( content is String ) {
readtomlstring( content )
} else {
false
}
}
// checks whether the tuple contains the given name or index
func tuple_contains( const tup @=, idx_or_name )
{
if( idx_or_name is String ) {
_tuple_index_of( tup, idx_or_name ) >= 0
} else {
_tuple_size( tup ) > idx_or_name
}
}
// pushes value to end of stack / tuple
func stack_push( stack @=, val @= )
{
_tuple_append( stack, val )
}
// pops value from stack / tuple
func stack_pop( stack @= )
{
const idx := _tuple_size( stack ) - 1
if( idx >= 0 ) {
const val := _tuple_val( stack, idx )
_tuple_remove( stack, idx )
val
} else {
void
}
}
func strreplacefirst( str @=, what, new, offset := 0 )
{
const pos := _strfind( str, what, offset )
if( pos >= 0 ) {
_strreplacepos( str, pos, _strlen( what ), new )
} else {
false
}
}
func strreplacelast( str @=, what, new, offset := -1 ) // offset -1 == whole string
{
const pos := _strfindreverse( str, what, offset )
if( pos >= 0 ) {
_strreplacepos( str, pos, _strlen( what ), new )
} else {
false
}
}
// trims the string if it starts or ends with characters in given set.
// e.g. strtrim( s, " \t\r\n", false, true ) will remove all spaces, tabs, carriage returns and new lines at the end of the string.
func strtrim( const str @=, set, leading := true, trailing := true )
{
def res := false
if( leading ) {
def c := 0
repeat {
const x := _strat( str, c ) // will return a complete UTF-8 code point.
if( _strfind( set, x, 0 ) >= 0 ) {
c := c + _strlen( x )
} else {
stop
}
}
if( c > 0 ) {
res := _strreplacepos( str, 0, c, "" )
}
}
if( trailing ) {
def i := _strlen( str ) - 1
def c := 0
repeat {
const x := _strat( str, i - c ) // will return a complete UTF-8 code point.
if( _strfind( set, x, 0 ) >= 0 ) {
c := c + _strlen( x )
} else {
stop
}
}
if( c > 0 ) {
res := _strreplacepos( str, i - c + 1, -1, "" ) or res
}
}
res
}
// splits the given string at every occurring separator and returns a tuple with the elements.
func strsplit( const str @=, separator, skip_empty := false )
{
def res := _tuple_create()
const str_size := _strlen( str )
if( str_size == 0 ) {
return res
}
const sep_size := _strlen( separator )
if( sep_size == 0 ) {
def res.0 := str
return res
}
def pos := 0
repeat {
const x := _strfind( str, separator, pos )
if( x >= 0 ) {
const s := _substr( str, pos, x - pos )
if( not skip_empty or _strlen( s ) > 0 ) {
_tuple_append( res, s )
}
pos := x + sep_size
if( pos == str_size ) {
if( not skip_empty ) {
_tuple_append( res, "" )
}
stop
}
} else {
// do we have a last element?
if( pos < str_size ) {
_tuple_append( res, _substr( str, pos, -1 ) )
}
stop
}
}
res
}
// joins all elements of a tuple to a string with given separator.
func strjoin( const tup @=, separator, add_leading := false, add_trailing := false )
{
def res := ""
if( add_leading ) {
res := separator
}
const last := _tuple_size( tup ) - 1
forall( idx in tup ) {
res := res % tup[ idx ]
if( idx != last ) {
res := res % separator
}
}
if( add_trailing ) { // this covers also empty tuple case
res := res % separator
}
res
}
// creates an utf-8 iterator for the given string and sets .cur to first utf-8 glyph.
func utf8_begin( const str @= )
{
def it := _tuple_create()
def it.cur := ""
def it._pos := 0
const it._base @= str
const it._size := _strlen( str )
it.cur := _strat( str, 0 )
it
}
// checks whether the given utf-8 iterator is at end.
func utf8_end( const it @= )
{
it._pos + _strlen( it.cur ) >= it._size
}
// advances the utf-8 iterator to next utf-8 glyph and updates .cur.
// if there is no more glyph it will point to the end of the string (\0).
func utf8_next( it @= )
{
const npos := it._pos + _strlen( it.cur )
it.cur := _strat( it._base, npos )
it._pos := npos
it
}
// computes power of n with integer exponent. if exp is a float it will get truncated. returns a f64.
func pow( n, exp )
{
const num := n + 0.0 // make a f64
def e := (+exp) as i64 // ensure an integer is used.
def res := 1.0
repeat {
if( e == 0 ) { stop }
if( e > 0 ) {
res := res * num
e := e - 1
} else {
res := res / num
e := e + 1
}
}
res
}
// convenience for call _sqrt with other types than f64
func sqrt( val )
{
_sqrt( val + 0.0 )
}
// convenience for call _trunc with other types than f64
func trunc( n )
{
_trunc( n + 0.0 )
}
// rounds down the given Number to next smaller integer as f64. e.g. 1.9 will yield 1.0, -2.1 will yield -3.0
func floor( n )
{
const num := (n + 0.0)
const trunced := _trunc( num )
if( trunced == num or num > 0.0 ) { // integer already or positive (then trunced is correct)
trunced
} else { // < 0.0 and not trunced
trunced - 1.0
}
}
// rounds up the given Number to next greater integer as f64. e.g. 1.1 will yield 2.0, -1.9 will yield -1.0
func ceil( n )
{
const num := (n + 0.0)
const trunced := _trunc( num )
if( trunced == num or num < 0.0 ) { // integer already or negative (then trunced is correct)
trunced
} else { // > 0.0 and not trunced
trunced + 1.0
}
}
// computes the hour, minute, second and (optionally) millisecond part of given time in seconds (e.g. from clock())
// note: hours can be greater than 23/24, it will not be cut at day boundary!
func timevals( t, HH @=, MM @=, S @=, ms @= 0 )
{
if( t is f64 and t >= 0.0 ) {
const secs := t as i64
HH := secs / 60 / 60
MM := (secs - (HH * 60 * 60)) / 60
S := (secs - (HH * 60 * 60) - (MM * 60))
ms := _f64toi64( (t - secs) * 1000.0 )
true
} else {
false
}
}
// builds a 24 hour wall clock string with the format HH:MM:SS.mmm (milliseconds are optional)
// note: if t is greater than 24 hours it will not be cut.
func timetostr( t, with_ms := false )
{
def HH := 0, def MM := 0, def S := 0, def ms := 0
if( timevals( t, HH, MM, S, ms ) ) {
const hours := if( HH < 10 ) { "0" % HH } else { "" % HH }
const minutes := if( MM < 10 ) { "0" % MM } else { "" % MM }
const seconds := if( S < 10 ) { "0" % S } else { "" % S }
if( with_ms ) {
const millis := if( ms < 10 ) { "00" % ms } else if( ms < 100 ) { "0" % ms } else { "" % ms }
"%(hours):%(minutes):%(seconds).%(millis)"
} else {
"%(hours):%(minutes):%(seconds)"
}
} else {
false
}
}
func rolldice( eyes := 6 )
{
random( 1, eyes )
}
//const ts_core_init_done_stamp := _timestamp()