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
'v' = VERSION
VERSION is a global variable containing the PikaScript engine version as a human readable text string.
args([@variables, ...])
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.
args(@x, @y)
'class' = classify(<value>)
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.
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'
<value> = coalesce(<values>|@variables, ...)
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.
coalesce(@gimmeVoidIfNotDefined)
coalesce(maybeVoid, perhapsThisAintVoid, 'nowIAmDefinitelyNotVoid')
<diff> = compare(<a>, <b>)
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.
compare('abc', 'def') < 0
compare('def', 'abc') > 0
compare('abc', 'abc') == 0
defaults([@variable, <value>, ...])
Assigns each <value> to each @variable if it does not exist. This function is useful for initializing global variables and optional function arguments.
defaults(@name, 'Smith')
defaults(@first, 'a', @last, 'z')
?deleted = delete(@variable)
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.
delete(@begone)
delete(@hurray[1972])
<result> = evaluate('code', [@frame])
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.
evaluate('3 + 3') == 6
evaluate('x = random(1)', @x)
?found = exists(@variable)
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.
exists(@::aglobal)
exists(@users['magnus lidstrom'])
include('filePath')
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'.
include('stdlib.pika')
'answer' = input('question')
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'.
name = input("What's your name? ")
<result> = invoke(['callee'], [>body], @args, [+offset = 0], [+count])
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'.
invoke('max', , @values)
invoke('(callback)', $0, @$, 1, 4)
'contents' = load('filePath')
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}'.
data = load('myfolder/myfile.txt')
<m> = max(<x>, <y>, [<z>, ...])
Returns the largest value of all the arguments.
max(5, 3, 7, 1, 4) == 7
max('Sleepy', 'Grumpy', 'Happy', 'Bashful', 'Dopey', 'Sneezy', 'Doc') === 'Sneezy'
max('Zero', '10', '5') === 'Zero'
<m> = min(<x>, <y>, [<z>, ...])
Returns the smallest value of all the arguments.
min(5, 3, 7, 1, 4) == 1
min('Sleepy', 'Grumpy', 'Happy', 'Bashful', 'Dopey', 'Sneezy', 'Doc') === 'Bashful'
min('Zero', '10', '5') === '5'
+offset = parse('code', ?literal)
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.
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
print('textLine')
Prints 'textLine' to the standard output, appending a newline character. (Sorry, but standard PikaScript provides no means for outputting text without the newline.)
print('Hello world!')
<result> = run('filePath', [<args>, ...])
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.
run('chess.pika')
htmlCode = run('makeHTML.pika', 'Make This Text HTML')
save('filePath', 'contents')
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}'.
save('myfolder/myfile.txt', 'No, sir, away! A papaya war is on!')
'code' = sourceFor(@variable|@container, ['prefix' = ''])
*** 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'.
save('AllGlobals.pika', sourceFor(@::))
evaluate(sourceFor(@wildmatch)) == wildmatch
evaluate(sourceFor(@::globalToLocalPlease), @$)
print(sourceFor(@myFunction, "\t\t"))
swap(@a, @b)
Swaps the contents of the variables referenced to by @a and @b. This function is useful in sorting algorithms.
swap(@master, @slave)
+exitCode = system('command')
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('error')
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.)
throw('Does not compute')
+secs = time()
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).
elapsed = time() - lastcheck
'literal' = toSource(<value>)
*** 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>.
toSource('string theory') === "'string theory'"
toSource('') === 'void'
toSource('{ /* get funcy */ }') === 'function { /* get funcy */ }'
evaluate(toSource(@reffy)) == @reffy
evaluate(toSource(>lambchop), @$) == (>lambchop)
'exception' = try(>doThis)
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.)
error = try(>data = load(file))
try(>1+1) === void
try(>1+'a') === "Invalid number: 'a'"
try(>throw('catchme')) === 'catchme'
vargs([@arguments, ...], , [@optionals, ...])
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().
vargs(@required1, @required2, , @optional1, @optional2)