utils

VERSION, args, classify, coalesce, compare, defaults, delete, evaluate, exists, include, input, invoke, load, max, min, parse, print, run, save, sourceFor, swap, system, throw, time, toSource, try, vargs


VERSION

Syntax

'v' = VERSION

Description

VERSION is a global variable containing the PikaScript engine version as a human readable text string.


args

Syntax

args([@variables, ...])

Description

Assigns arguments to named variables. Pass a reference to a local variable for each argument your function expects. The caller of your function must pass exactly this number of arguments or an exception will be thrown.

Examples

args(@x, @y)

See Also

vargs


classify

Syntax

'class' = classify(<value>)

Description

Examines <value> and tries to determine what "value class" it belongs to:

- 'void' (empty string)
- 'boolean' ('true' or 'false')
- 'number' (starts with a digit, '+' or '-' and is convertible to a number)
- 'reference' (starting with ':' and containing at least one more ':')
- 'function' (enclosed in '{ }' or begins with '>:' and contains one more ':')
- 'native' (enclosed in '< >')
- 'string' (if no other match)

Notice that since there are no strict value types in PikaScript the result of this function should be considered a "hint" only of what type <value> is. For example, there is no guarantee that a value classified as a 'function' actually contains executable code.

Examples

classify(void) === 'void'
classify('false') === 'boolean'
classify(123.456) === 'number'
classify(@localvar) === 'reference'
classify(function { }) === 'function'
classify(>lambda) === 'function'
classify('<print>') === 'native'
classify('tumbleweed') === 'string'

coalesce

Syntax

<value> = coalesce(<values>|@variables, ...)

Description

Returns the first <value> in the argument list that is non-void, or the contents of the first @variables that exists (whichever comes first). void is returned if everything else fails.

A word of warning here, if a string value happens to look like a reference (e.g. '::') it will be interpreted as a such which may yield unexpected results. E.g. coalesce('::uhuh', 'oops') will not return 'oops' if a global variable named 'uhuh' exists.

Examples

coalesce(@gimmeVoidIfNotDefined)
coalesce(maybeVoid, perhapsThisAintVoid, 'nowIAmDefinitelyNotVoid')

See Also

defaults, exists


compare

Syntax

<diff> = compare(<a>, <b>)

Description

Returns 0 if <a> equals <b>, -1 if <a> is less than <b> and 1 if <a> is greater than <b>. This function is useful in sorting algorithms.

Examples

compare('abc', 'def') < 0
compare('def', 'abc') > 0
compare('abc', 'abc') == 0

See Also

qsort, swap


defaults

Syntax

defaults([@variable, <value>, ...])

Description

Assigns each <value> to each @variable if it does not exist. This function is useful for initializing global variables and optional function arguments.

Examples

defaults(@name, 'Smith')
defaults(@first, 'a', @last, 'z')

See Also

coalesce


<delete>

Syntax

?deleted = delete(@variable)

Description

Deletes the variable referenced to by @variable and returns true if the variable existed and was successfully deleted.

Notice that this function can only delete a single variable at a time. This means only a single "element" in a "container" as well. Use prune() to delete an entire "plain old data" container and destruct() to delete an object.

Examples

delete(@begone)
delete(@hurray[1972])

See Also

destruct, exists, prune


<evaluate>

Syntax

<result> = evaluate('code', [@frame])

Description

Evaluates 'code' and returns the result. You can decide which frame should execute the code by supplying a reference in @frame. Without @frame, code is executed in its own frame just as if you would call a function. Only the "frame identifier" of @frame is used.

You may for example pass @$ to execute in the current frame, or @^$ to execute in the caller's frame (the '$' is there to reference the correct frame even if it is a lambda expression), or @:: to execute in the global frame.

Examples

evaluate('3 + 3') == 6
evaluate('x = random(1)', @x)

See Also

bake, invoke, parse, run, sourceFor, toSource


<exists>

Syntax

?found = exists(@variable)

Description

Returns true if the variable referenced to by @variable is defined. Notice that this function does not "fall back" to the global frame if a local variable does not exist. Therefore you should always prefix the variable name with '::' if you want to check for the existance of a global variable or function.

Examples

exists(@::aglobal)
exists(@users['magnus lidstrom'])

See Also

coalesce, defaults, delete


include

Syntax

include('filePath')

Description

Runs a PikaScript source file as with run() but only if 'filePath' has not been "included" before. The function determines this by checking the existance of a global ::included[filePath]. It defines this global after completing execution the first time. (run() does not define or use this global.) Use include() with source files that defines library functions and constants, e.g. 'stdlib.pika'.

Examples

include('stdlib.pika')

See Also

run


<input>

Syntax

'answer' = input('question')

Description

Prints 'question' and returns a line read from the standard input stream (excluding any terminating line feed characters). May throw 'Unexpected end of input file' or 'Input file error'.

Examples

name = input("What's your name? ")

See Also

print


<invoke>

Syntax

<result> = invoke(['callee'], [>body], @args, [+offset = 0], [+count])

Description

Calls 'callee' (or >body) with the argument list @args. The difference between using 'callee' or >body is that the former should be a string with a function name, while the latter should be an actual function body. If both arguments are present, >body will be executed, but the called function's $callee variable will be set to 'callee'. For debugging purposes it is recommended that you use the 'callee' argument.

+offset can be used to adjust the element index for the first argument. +count is the number of arguments. If it is omitted, [@args].n is used to determine the count.

May throw 'Too few array elements'.

Examples

invoke('max', , @values)
invoke('(callback)', $0, @$, 1, 4)

See Also

evaluate, invokeMethod, run


<load>

Syntax

'contents' = load('filePath')

Description

Loads a file from disk and returns it as a string. The standard implementation uses the file I/O of the standard C++ library, which takes care of line ending conversion etc. It can normally only handle ASCII text files. May throw 'Cannot open file for reading: {filePath}' or 'Error reading from file: {filePath}'.

Examples

data = load('myfolder/myfile.txt')

See Also

save


max

Syntax

<m> = max(<x>, <y>, [<z>, ...])

Description

Returns the largest value of all the arguments.

Examples

max(5, 3, 7, 1, 4) == 7
max('Sleepy', 'Grumpy', 'Happy', 'Bashful', 'Dopey', 'Sneezy', 'Doc') === 'Sneezy'
max('Zero', '10', '5') === 'Zero'

See Also

min


min

Syntax

<m> = min(<x>, <y>, [<z>, ...])

Description

Returns the smallest value of all the arguments.

Examples

min(5, 3, 7, 1, 4) == 1
min('Sleepy', 'Grumpy', 'Happy', 'Bashful', 'Dopey', 'Sneezy', 'Doc') === 'Bashful'
min('Zero', '10', '5') === '5'

See Also

max


<parse>

Syntax

+offset = parse('code', ?literal)

Description

Parses 'code' (without executing it) and returns the number of characters that was successfully parsed. 'code' is expected to start with a PikaScript expression or in case ?literal is true, a single literal (e.g. a number). If ?literal is false, the parsing ends when a semicolon or any unknown or unexpected character is encountered (including unbalanced parentheses etc). The resulting expression needs to be syntactically correct or an exception will be thrown.

You can use this function to extract PikaScript code (or constants) inlined in other text. You may then evaluate the result with evaluate() and continue processing after the extracted code. Pass true for ?literal in case you want to evaluate a single constant and prevent function calls, assignments etc to be performed. Valid literals are: 'void', 'false', 'true', numbers (incl. hex numbers and 'infinity' of any sign), escaped strings (with single or double quotes), natives (enclosed in '< >'), function or lambda definitions.

Examples

parse('3+3', false) == 3
parse('3+3', true) == 1
parse('1 + 2 * 3 ; stop at semicolon', false) == 10
parse(' /* leading comment */ code_here /* skip */ /* trailing */ /* comments */ but stop here', false) == 74
parse('stop after space after stop', false) == 5
parse('x + x * 3 ) * 7 /* stop at unbalanced ) */', false) == 10
parse('+infinity', true) == 9
parse('"stop after the \", but before" this text', true) == 31

See Also

escape, evaluate, run, tokenize


<print>

Syntax

print('textLine')

Description

Prints 'textLine' to the standard output, appending a newline character. (Sorry, but standard PikaScript provides no means for outputting text without the newline.)

Examples

print('Hello world!')

See Also

input


run

Syntax

<result> = run('filePath', [<args>, ...])

Description

Loads and executes a PikaScript source file. The code is executed in the "closure" of the global frame, which means that variable assignments etc work on globals. The code can still use temporary local variables with the $ prefix. The passed <args> are available in $1 and up. $0 will be 'filePath'. The returned value is the final result value of the executed code, just as it would be for a function call. The first line of the source code file may be a "Unix shebang" (in which case it is simply ignored). Use include() if you wish to avoid a file from running more than once.

Examples

run('chess.pika')
htmlCode = run('makeHTML.pika', 'Make This Text HTML')

See Also

evaluate, include, invoke


<save>

Syntax

save('filePath', 'contents')

Description

Saves 'contents' to a file (replacing any existing file). The standard implementation uses the file I/O of the standard C++ library, which takes care of line ending conversion etc. It can normally only handle ASCII text files. May throw 'Cannot open file for writing: {filePath}' or 'Error writing to file: {filePath}'.

Examples

save('myfolder/myfile.txt', 'No, sir, away! A papaya war is on!')

See Also

load


sourceFor

Syntax

'code' = sourceFor(@variable|@container, ['prefix' = ''])

Description

*** WARNING, THIS FUNCTION IS SLIGHTLY BROKEN AND MAY BE REMOVED. USE AT OWN RISK! ***

Creates source code for recalling the definition of @variable or @container (with all its sub-elements). The created code can be used with evaluate() to recall the definition in any given frame. For example: evaluate('code', @$) would recreate variables in the current local frame and evaluate('code', @::) would create them in the global frame.

Each output line will be prefixed with 'prefix'.

Examples

save('AllGlobals.pika', sourceFor(@::))
evaluate(sourceFor(@wildmatch)) == wildmatch
evaluate(sourceFor(@::globalToLocalPlease), @$)
print(sourceFor(@myFunction, "\t\t"))

See Also

dump, evaluate, toSource


swap

Syntax

swap(@a, @b)

Description

Swaps the contents of the variables referenced to by @a and @b. This function is useful in sorting algorithms.

Examples

swap(@master, @slave)

See Also

compare, qsort


<system>

Syntax

+exitCode = system('command')

Description

Tries to execute 'command' through the operating system's command interpreter. +exitCode is the return value from the command interpreter (a value of 0 usually means no error). May throw 'Error executing system command: {command}'.


<throw>

Syntax

throw('error')

Description

Throws an exception. 'error' should describe the error in human readable form. Use try() to catch errors. (PikaScript exceptions are standard C++ exceptions. It is up to the host application how uncaught exceptions are handled.)

Examples

throw('Does not compute')

See Also

try


<time>

Syntax

+secs = time()

Description

Returns the system clock as "epoch time", i.e. the number of seconds that has passed since a specific reference date (usually January 1 1970).

Examples

elapsed = time() - lastcheck

toSource

Syntax

'literal' = toSource(<value>)

Description

*** WARNING, THIS FUNCTION IS SLIGHTLY BROKEN AND MAY BE REMOVED. USE AT OWN RISK! ***

Returns the source code literal for <value>. I.e. 'literal' is formatted so that calling evaluate('literal') would bring back the original <value>.

Examples

toSource('string theory') === "'string theory'"
toSource('') === 'void'
toSource('{ /* get funcy */ }') === 'function { /* get funcy */ }'
evaluate(toSource(@reffy)) == @reffy
evaluate(toSource(>lambchop), @$) == (>lambchop)

See Also

dump, evaluate, sourceFor


<try>

Syntax

'exception' = try(>doThis)

Description

Executes >doThis, catching any thrown exceptions and returning the error string of the exception. If no exception was caught, void is returned. The returned value of >doThis is discarded. (Although PikaScript exceptions are standard C++ exceptions you can only catch PikaScript errors with this function.)

Examples

error = try(>data = load(file))
try(>1+1) === void
try(>1+'a') === "Invalid number: 'a'"
try(>throw('catchme')) === 'catchme'

See Also

throw


vargs

Syntax

vargs([@arguments, ...], , [@optionals, ...])

Description

As args() but you may define arguments that are optional. The caller of your function must pass all required arguments or an exception will be thrown. An exception will also be thrown if the caller passes more optional arguments than present in vargs(). An easy way to assign default values for optional arguments is with the default() function. Alternatively you may want to use coalesce().

Examples

vargs(@required1, @required2, , @optional1, @optional2)

See Also

args, coalesce, defaults