The 8th™ Programming Language

Word list version 24.06

Copyright © AHT Associates LLC, All Rights Reserved
8th™ is a trademark of AHT Associates LLC

Words by namespace

The following is an exhaustive list of the built-in words in 8th, arranged by namespace, including descriptions of the words and their SEDs. This information is the same as that provided by the console help.

2fa

Namespace: 2fa
Description: Two factor authentication

word sed/description
gen-secret -- b (as of 21.02)
needs 2fa/totp

Generate a secret key for the TOTP algorithm to use. Returns a 16 byte random buffer.

gen-url m -- url (as of 21.02)
needs 2fa/totp

Takes a map with the parameters to be converted to a QR code or base64 encoded for Authy or Google Authenticator, etc.

Valid keys are:

validate-code key code ndigits -- T (as of 21.02)
needs 2fa/totp

Takes the TOTP secret and the code entered by the user, and validates the code

Application

Namespace: app
Description: Application

word sed/description
8thdir -- s

Returns the name of the (OS specific) directory where 8th stores data; this is almost the same as app:datadir , but is always the ".8th" directory.

asset s -- b

Read an "asset", which is a resource bundled with the application. Returns a buffer containing the resource content. The parameter s refers to a "relative path". That path is relative to where the script or application appdata is located. So if the script is in src/app.8th then the asset "image/a.png" is in "src/image/a.png". For a compiled application, the appdata is created with bin/build .

atrun opt --
needs win/atrun

given a map opt, arrange to launch the indicated application at a specific time. the keys in the map are: "exe" - a string which is the name of the executable to run (required); "args" - an array of strings which has the command-line arguments to the application; "when" - a date which indicates the time at which the application should be run (required); "dir" - the directory where the exe should run (not effective on linux/rpi).

atrun opt --
needs mac/atrun

Given a map opt, arrange to launch the indicated application at a specific time. The keys in the map are: "exe" - a string which is the name of the executable to run (required); "args" - an array of strings which has the command-line arguments to the application; "when" - a date which indicates the time at which the application should be run (required); "dir" - the directory where the exe should run (not effective on Linux/RPI).

atrun m --
needs lin/atrun

given a map, arrange to launch the indicated application at a specific time. The keys in the map are:

  • exe: string which is the name of the executable to run (required)
  • args: array of strings which has the command-line arguments to the exe
  • when: date which indicates the time at which the application should be run (required)
  • dir: string directory where the exe should run (not effective on linux/rpi).

Requires "atd" be installed and running.

basedir -- s

Returns a string which is the name of the (OS specific) application-accessible directory.

basename -- s (as of 23.04)

Returns the name of the executable 8th is named as. "8th" , unless compiled as a standalone program.

config-file-name s -- s (as of 21.08)
needs utils/config-file

Given a base-name, return the OS-specific path to a "private" configuration file It is the result of app:privdir plus the base-name you give.

current -- (as of 18.01)

Launches a system-defined browser to the canonical 8th "current" page, with your user id and version of 8th. Will give you the option to refresh your build if you like.

datadir -- s

Returns the OS specific name of the directory where this application stores data.

display-moved n -- (as of 23.08)
DEFFERED

Invoked when the primary monitor has moved or changes position with another monitor. n is the index of the affected display.

exename -- s

Returns a string which is the running executable's full path name.

localechanged -- (as of 21.08)
DEFFERED

Invoked when the user changes the system locale. After this message is received, you can get the new current locale using os:lang and os:region , or all the user's chosen locales with os:locales .

lowmem -- (as of 20.01)
DEFFERED

Invoked if the OS is running low on memory. Free up resources if you can.

main --

If you define a word with this name, your application will start there. Otherwise, the default version will run, which just invokes G:cold and the REPL.

name -- v (as of 21.06)

A var which contains the name of the current application. The default value is "8th", so you probably want to change it, e.g. "myappname" app:name ! .

onback -- (as of 24.05)
DEFFERED

Invoked when the "back button" is pressed (Android only). The default d: behavior invokes bye .

oncrash s -- (as of 18.06)

If the application crashed, this word is invoked with a message.

opts! s x -- (as of 19.07)

Stores the value x under the key s for retrieval by app:opts@ .


See also: app:opts@
opts@ s -- x (as of 19.07)

Returns the value v stored in the key s by app:opts! . Values are application-global, and are typically used to pass information to libraries upon loading. Ex: G:help uses the "help.width" key.


See also: app:opts!
orientation n -- (as of 16.13)
DEFFERED

Invoked (on mobile devices) when the device orientation has changed. n is 1 for 'upright', 2 for 'upside down', 3 for 'rotated clockwise' and 4 for 'rotated anti-clockwise'.

orientation! n -- (as of 20.04)

On mobile devices (Android only for the moment) sets the permitted orientation: 1 for 'upright', 2 for 'upside down', 3 for 'rotated clockwise' and 4 for 'rotated anti-clockwise'.

pid -- n (as of 17.06)

Returns the application's OS-specific process-id.

post-main -- (as of 20.01)
DEFFERED

For non-mobile applications only. Invoked just after app:main exits.

pre-main -- (as of 20.01)
DEFFERED

For non-mobile applications only. Invoked prior to app:main .

privdir -- s (as of 21.08)

Returns the os-specific "private dir" (e.g. "/etc/" on POSIX systems)

raise n -- | s -- (as of 19.09)

Sends ("raises") the given signal to the app. If it's a number, that signal number is raised; if it's a string, then the signal of that name is raised. Only signals which 8th traps by default can be named.

Ex: "USR1" app:raise works, but "KILL" app:raise does not.


See also: app:signal app:trap
read-config s -- m (as of 21.08)
needs utils/config-file

Given the config-file base-name, return a buffer containing the contents of the file (or null, if there's nothing there)

read-config-map s -- m (as of 21.08)
needs utils/config-file

Given the config-file base-name, return a map with values in the JSON formatted map in that file. Returns an empty map if the file does not contain one.

read-config-var s name -- x (as of 21.08)
needs utils/config-file

Given the config-file base-name, and the name of a variable (a key in the map therein), return the value of the key.

request-perm s -- T (as of 20.05)

ANDROID: request the OS-specific permission (e.g. "android.permission.RECORD_AUDIO"). Returns true if the permission was granted.

restart -- (as of 17.06)

Restarts the application from the beginning, launching a new process.

resumed --
DEFFERED

Mobile only. Invoked when the application is about to be resumed. TOS is true if app has been resumed, false if preparing to resume. Take care of restoring application state here, saved during app:suspended .


See also: app:suspended
signal s -- (as of 19.09)
DEFFERED

Invoked when the OS signal s has been received. Traps SIGINT, SIGTERM, and SIGABRT on all platforms. On other than Windows, it also traps SIGHUP, SIGUSR1, and SIGUSR2. The signal name is passed in s (e.g. "INT"). For signals trapped using app:trap and which are unknown to 8th, the numeric value of the signal is converted to a string and passed in. The default behavior is to print the name of the signal received and quit. A signal handler is not guaranteed to be invoked in any particular task, so be careful!


See also: app:trap app:raise
standalone -- v (as of 17.10)

A var which holds the value true if the app is running as a built, standalone, application. It is false otherwise.

standalone! T -- (as of 24.06)

Sets app:standalone . If true , w:forget s words which are security risks. The build utility inserts true app:standalone! in built applications.

subdir s -- s' (as of 17.01)

Returns the name of the subdirectory of the (OS specific) directory where 8th stores data. s may or may not exist on the system, this word simply returns a composed name.

suspended T --
DEFFERED

Mobile only. Invoked when the application is about to be suspended. TOS is true if the app has been suspended, false if preparing to suspend. Take care of saving application state here, in preparation for app:resumed .


See also: app:resumed
sysquit -- T
DEFFERED

Invoked if the system requests that the application shut down. The default simply returns true , which means "quit". If you do not want to allow the system to close the application, you should return false instead.

Note: denying the OS doesn't mean you will succeed...

terminated -- (as of 20.01)
DEFFERED

Invoked if the OS is terminating the application for some reason.

ticks -- n (as of 24.06)

Gets the number of 'ticks' the app has been running, since the app was loaded.


See also: t:ticks
timeout n -- (as of 22.01)
needs utils/timeout

Creates a background task which waits for n seconds before invoking app:timed-out (which does nothing, by default) and then invoking 1 die .

trap n T -- (as of 19.09)

Tell 8th to trap the signal whose number is n (this will be OS-specific). If T is true, the signal should be trapped; otherwise, it should be ignored. The deferred word app:signal will be invoked if the signal is intercepted. The acceptable values of n are OS-specific.


See also: app:signal app:raise

Array

Namespace: a
Description: Arrays are sequentially ordered containers accessed by numeric index

word sed/description
! a ix x -- a

Put the item x in the array at index ix . If the index is larger than the largest current index, the array will be resized and any empty spots created will be filled with null . If ix is negative, then the element at the index from the end of the array will be modified. For example, an index of "-1" will modify the last element.


See also: a:@
+ a1 a2 -- a1

Append contents of array a2 to a1 , modifying a1 .

- a ix -- a

Remove the item at index ix from the array a , moving other items over to fill the gap: a is modified. If you just want to remove an item from the array without changing the position of other elements, simply store null in the position of the item you want to remove. If ix is less than 0 the item that far from the end of the array is removed.

/ a ix -- a1 a2 | a w -- a1 a2 (as of 21.01)

Splits an existing array into two parts at the index. If the index is less than 0, splits at that index from the end of the array. If given a word , then that word determines which array (a1 or a2) to split the item to. In that case the SED of the word must be ix x -- T where it returns true for a1 , or false for a2 .

2each a1 a2 w -- a1 a2 (as of 18.08)

Iterates over two arrays, invoking w for each corresponding element in them. w 's SED is: n x1 x2 -- ; that is, it is passed both the index of the items and the items themselves. The arrays are not available on the stack while it is running, to avoid consistency problems. w must consume its inputs. Will stop iterating on break or once the shorter of the two inputs is exhausted. Obeys G:step .

NOTE: You must not modify the array being iterated, while it is being iterated! Modifying the array while it is being iterated may throw an exception.


See also: a:each a:each! a:x-each
2map a1 a2 w -- a' (as of 18.08)

Similar to a:map , but takes two arrays and invokes w on the corresponding elements of them. If the arrays are not of equal size, will stop after processing the shorter one; thus, the result will be of the same length as the shorter of the two inputs.


See also: a:map a:2map=
2map+ a1 a2 w n1 n2 -- a' (as of 18.08)

Similar to a:2map , but takes additional parameters:

  • n1 : the number of items of a to pass in each time
  • n2 : number of items to advance before creating the next slice

The SED of w is a3 a4 -- x , where a3 is an n1 sized slice of a1 , and a4 of a2 .

By default, the initial slice index increments by 1 each iteration; by using step (inside w ) you can make that any value you wish. The result is a new array with the values returned by w on each iteration.

Ex: [1,2,3,4] [10,20,30,40] ( 2 a:close ) 2 1 a:2map+ yields: [[[1,2],[10,20]],[[2,3],[20,30]],[[3,4],[30,40]]]


See also: a:2map
2map= a1 a2 w -- a1 (as of 18.08)

Same as a:2map , but modifies the original array.


See also: a:map a:2map
<> a ix1 ix2 -- a (as of 22.07)

Swaps the array items at those indices. Ex: [10,20,30] 1 2 a:<> returns [10,30,20] .

= a1 a2 w -- a1 a2 T (as of 18.04)

Compares the two arrays using the word w to compare each item. The SED for w is: x1 x2 -- T , where T is true if the items are equal, otherwise false. Arrays must have equal length to be considered equal, and each compared element must have the same type.

@ a ix -- a x | a a1 -- a a2

Returns the item in the array at index ix . If ix is negative, get the item from the end of the array, e.g. "-1" corresponds to the last element. If ix is out of bounds, null is returned (though null might also be a valid element! Use a:exists? to distinguish). If the index is an array of numbers, returns another array with values corresponding to the indices in a1 .


See also: a:! a:exists?
@? a ix x -- a x'

Same as a:@ , but if the item at that index doesn't exist, supplies the default value x . If x is an array, then if ix is also an array, the value returned will be from the corresponding element of the x array (last element used for all corresponding elements beyond the original's bounds).


See also: a:! a:exists? m:@?
[]! a n x -- a (as of 20.08)

Same as a:! , but if the index n doesn't exist or is not an array, a new array is created, the existing value if any is pushed to it, and the new value is pushed into it. Basically, accumulates values to the index.

Ex: [10,20,30] 1 21 a:[]! results in [10,[20,21],30]

_@ a n -- x (as of 19.07)

Same as a:@ , but removes the array from the stack.


See also: a:@
all a w -- a T
needs python/any

Iterates the array, invoking w on each one. If all of the items return true from w then returns true; otherwise returns false. Short-circuits on first 'false' result.

any a w -- a T
needs python/any

Iterates the array, invoking w on each one. If any of the items returns true from w then returns true; otherwise returns false. Short-circuits on first 'true' result.

bsearch a x w -- a ix (as of 16.01)

Search for the item x in a sorted array, using the comparison word w (which was used for the sort!), whose SED is: x1 x2 -- n , where n is a negative number if the first item is less than the second, 0 if they're equal, and positive if the first is greater than the second.

Returns the index of the matching item, or null if there was no match.

Note: The array must have been sorted in ascending order using the same comparator w in order for this to work correctly!

centroid a -- a'
needs array/centroid

Given an array of points, where each point is an array of x,y coordinates, return an array which consists of the centroids of those points. May be any dimension as long as each point is the same dimension.

clear a -- a

Remove all elements from the array. Similar to repeatedly invoking a:pop drop .

close x1 x2 x3 ... xN n -- a

Create an array from n items on the stack. This is the inverse of a:open . If n is 0 or negative, will only consume TOS (e.g. n ).


See also: a:open
cmp a1 a2 w -- a1 a2 n (as of 23.08)
needs array/cmp

Compare two arrays. Similar to 'a:=', but given a comparator word (like s:cmp or n:cmp) The first non-equal element terminates the comparison, and 'n' is the result of the comparator on that element. Result 'n' is 0 if arrays compare 'equal', '-1' if a1 is 'less'

diff a1 a2 w -- a1 (as of 22.02)

Removes from a1 all elements which are in a2 . The w word should return true if the items are equal.

dot a1 a2 w1 w2 -- x

Generalized "dot product" of the two arrays a1 and a2 . If they are not the same length, returns null . Otherwise, invokes the word w1 on each corresponding item in each array, and then invokes the word w2 on each pair of results, accumulating them into a result x . Ex: [1,2] [3,4] ' n:* ' n:+ a:dot results in the number 11.

each a w -- a

Iterate over the array, invoking w for each element in it. The SED of w is ix x -- , where ix is the index of the item x in the array.

While running, the array is not available on the stack, to avoid consistency problems. w must consume both items.

NOTE: You must not modify the array being iterated, while it is being iterated! Modifying the array while it is being iterated may throw an exception.


See also: a:each!
each! a w -- a (as of 19.04)

Same as a:each , but only passes the item, omitting the index, to the word. The SED of w is x -- .

NOTE: You must not modify the array being iterated, while it is being iterated! Modifying the array while it is being iterated may throw an exception.


See also: a:each
each-par a w n -- a (as of 23.09)
needs array/parallel

Splits the array into n sub-arrays and invokes a:each! on each of them in a separate task, then recombines them.

each-slice arr wrd sz -- arr
needs array/each-slice

Split array arr into slices of size sz elements, and feed each slice to the word wrd. That callback gets the stack slicenumber slice on its stack.

exists? a ix -- a T

Returns true if there is a value defined for the given index in the array. This is necessary because requesting an arbitrary index from an array will always succeed, returning null if the index does not exist as well as if the value stored is actually null . If the index is negative, it is taken as that many from the end.

filter a w -- a'

Creates an array, whose elements are those from the initial array for which the word w returns true . The SED of w is x -- T , where x is each element of a in turn. It must consume each item it is given.

While this word is running, the original array is not on the stack so it is possible to access items which were under it.


See also: a:reduce a:map
filter-par a w n -- a' (as of 23.09)
needs array/parallel

Splits the array into n sub-arrays and invokes a:filter on each of them in a separate task, then recombines them.

generate w n1 n2 -- a | w -- a (as of 18.08)

Loops over the numeric range [n1, n2] , invoking w on each number. The result in TOS is pushed onto the resultant array.

If given only a word, then that word is invoked repeatedly with a SED of n -- x where n is the current index (starting at 0) and x is what TOS is after w is invoked. The repetition stops after break is invoked.

group a w -- m (as of 18.08)

Group elements in an array, creating a map whose values are arrays containing items with the same grouping. The word used to group the items takes an array element and returns an item which is the group to which that element belongs, SED x -- s .

indexof a x w -- a ix (as of 16.01)

Search for the item x in the array, using the comparison word w , whose SED is: x1 x2 -- T . It takes two items of the given type and returns true if they match, or false otherwise.

Returns the index of the matching item, or null if there was no match.

insert a1 a2 ix -- a3

Create a new array by inserting the contents of array a2 into the array a1 at offset ix . If the offset is negative, it means "from the end of the array". If ix is greater than the current number of items in a1 , the missing items will be null .


See also: a:+
intersect a1 a2 w -- a3 (as of 22.02)

Produces the "intersection" of two arrays over the comparator word. The resultant array contains only those values common to the input arrays (without duplication).

join a sep -- s

Inverse of s:/ . Joins an array of strings, inserting the string sep between each pair of items; return new string s .


See also: s:/
len a -- a n

Returns the length of the array, e.g. the highest index occupied plus 1 (indices start at 0). The actual number of items contained may be less than the array's length, because one can insert an item at any index (subject to system memory constraints).

len' a -- n (as of 24.03)

Same as a:len but does not leave the array on the stack.

len2 a1 a2 -- a1 a2 n1 n2 (as of 24.03)

Given two arrays, returns their respective lengths. Much faster and more efficient than the hard way.

map a w -- a'

Creates an array, whose elements are formed by executing the word w for each element of the original array. The SED of w is x -- x' , where x' may be the same as x . The mapping must consume the element given, producing a single result on TOS, which becomes the corresponding element in the new array.

While this word is running, the original array is not on the stack so it is possible to access items which were under it.


See also: a:filter a:reduce
map+ a w n1 n2 -- a' (as of 18.08)

Similar to a:map , but takes additional parameters:

  • n1 : the number of items of a to pass in each time
  • n2 is the number of items to advance before creating the next slice

The SED of w is a -- x , where a is an n1 sized array slice of the original array. By default, the initial slice index increments by 1 each iteration; by using step (inside w ) you can make that any value you wish.


See also: a:map
map-par a w n -- a' (as of 23.09)
needs array/parallel

Splits the array into n sub-arrays and invokes a:map on each of them in a separate task, then recombines them.

map= a w -- a (as of 18.05)

Same as a:map , but modifies the original array.


See also: a:map
maxlen a -- n (as of 23.01)
needs array/maxlen

Returns the maximum (character) length of an array of strings

mean a -- a n
needs math/mean

Calculate the mean (average) value of an array of numbers. Should be faster than a:mean&variance if all you need is the arithmetic mean

mean&variance a -- a a'
needs math/mean

Uses the Knuth variance algorithm to calculate mean and variance in one pass. Returns an array containing [sample variance, mean, count, population variance, stddev]

merge a1 a2 w -- a3 (as of 21.06)

Combines the two arrays as in a 'merge sort', using the given word as a comparator. If the arrays are not already sorted, garbage will result.

new -- a (as of 17.05)

Create a new, empty array.

op! a ix w -- a (as of 17.01)

Invokes w on the array contents at the specified index, replacing the current contents. Any operands to w should appear in their normal stack order under w .

open a -- x1 x2 x3 ... xN

"Open up" the contents of the array a , spilling it onto the stack. Faster and more clear than manually unpacking the array. Be careful not to overflow the stack! Useful for example after using G:unpack so you can access the data easily. Pair with a:close (you need to add back the length in TOS for that to work).


See also: a:close
pigeon a1 a2 x w -- x' (as of 21.09)

Performs a 'pigeonhole operation', meaning that x is compared using w to successive (ascending, ordered) values in a2 . The index of the item which is "greater" than x is used to look-up a value in a1 . Ex:

["red", "blue", "green"] [10,20] 15 ' n:cmp a:pigeon

returns "blue", since 15 is between 10 and 20.

pivot a -- a' (as of 22.08)

"Pivots" the array. If it consists of arrays (all the same length) like [[x1,x2,...], [y1,y2,...]] then the pivot creates a new array [[x1,y1,...], [x2,y2,...]] . The length of the largest array element is taken to be the length of all elements (and null will be in the pivot for items not in smaller arrays). If any of the elements of a is not itself an array, returns null .

pop a -- a x

Pop the item x from the array; that is, from the highest index in the array. If the array was empty, returns null .

Note: Since it is possible that null was actually stored in the array, use a:exists? to remove ambiguity.


See also: a:push a:@ a:!
push a x -- a | x a -- a

Push the item x onto the array. The array will expand as needed. After the push, x will occupy the highest index in the array.

The order may be either a x or x a . If x is itself an array, then you must use the order a x in order to achieve the desired result.


See also: a:pop a:@ a:!
push' a x -- (as of 24.03)

Same effect as a:push drop but more efficient.

qsort a w -- a (as of 18.08)

Sorts the array using the "quicksort" algorithm and the comparison word w .

The SED of w is: x1 x2 -- n , where n is 0 if the items are equal, positive if x1 ≥ x2 , negative otherwise.

Note: If the comparison function modifies the elements it is given, they will be modified in the original array! It is typically slower than a:sort ; as well as not being a stable sort, but is uses less memory.


See also: a:sort
randeach a w -- a (as of 18.08)

Same as a:each , but iterates the array in a random order. Because of that, it does not obey step .

NOTE: You must not modify the array while it is being iterated!

reduce a w x -- x'

Iterate over the array, invoking w for each element in a with the accumulated value.

The SED of w is x elem -- x' , where elem is an element in a , and x is the accumulated value so far, starting with x .

While running, the original array is not on the stack.

Ex: [1,2,3] ' n:+ 0 a:reduce sums the array giving 6.


See also: a:map a:filter
reduce+ a w x n1 n2 -- x' (as of 18.08)

Same as a:reduce , but takes additional parameters:

  • n1 : the number of items of a to pass in each time
  • n2 : the number of items to advance before creating the next slice

As with a:map+ , invoking step (inside w ) will make it advance by step items. The SED of w is x a -- x' , where a is an array with n1 items from the original, and x is the accumulated value so-far.

Ex: [1,2,3,4,5,6] ( a:open n:* n:+ ) 0 2 1 a:reduce+ gives '70', which is 1*2 + 2*3 + 3*4 + 4*5 + 5*6 .

[1,2,3,4,5,6] ( a:open n:* n:+ ) 0 2 2 a:reduce+ gives '50', which is 1*3 + 2*4 + 3*5 + 4*6 .


See also: a:reduce
remove a x -- a n (as of 20.01)

Removes all instances of the item x from the array. Returns the number of instances found and removed.

rev a -- a

Given an array, modifies it so the elements are in reverse order.

rindexof a x w -- a ix (as of 21.09)

Same as a:indexof , but searches from the end of the array.

shift a -- a x

Removes the item x from the first position in the array (e.g. a[0] ) and puts it on TOS. This makes the array one element shorter, and shifts all remaining elements one lower. Like a:pop but from the start of the array.


See also: a:slide a:push a:pop
shuffle a -- a

Randomly shuffles the entries in the array Uses rand-pcg , so it is not cryptographically random.

slice a ix n -- a'

Returns a slice of the array a beginning at index ix for n items. A negative value of ix means "take from the end of the array". If ix+n is greater than the number of items in a (starting from ix ), then the slice will be only as large as the number of items available in a . A negative value of n means "take the rest of the array".

slice+ a ix n step -- a' (as of 18.04)

Same was a:slice but also takes a "step" amount, which is how many items to advance before creating next slice.

Ex: [0,1,2,3,4] 1 -1 2 a:slice+ returns [1,3]


See also: a:slice
slide a x -- a

Puts x in the first position in the array (e.g. a[0] ), moving all remaining items up one index. Like a:push but at the beginning of the array.


See also: a:shift a:push a:pop
smear a n -- a (as of 22.04)

Smears the last item in the array, duplicating it to fill the array up to n items. Ex: [1,2,3] 5 a:smear results in [1,2,3,3,3] .

sort a w -- a

Sorts the array using the "timsort" algorithm and the comparison word w . Exactly the same as a:qsort , but uses a stable sort instead.

The SED of w is: x1 x2 -- n , where n is 0 if the items are equal, positive if x1 ≥ x2 , negative otherwise.

Note: If the comparison function modifies the elements it is given, they will be modified in the original array! This sort is generally faster than a:qsort , but uses more memory.


See also: a:qsort
split a n -- a' (as of 23.09)

Splits the array into one containing n equal sub-arrays. So [1,2,3,4] 2 a:split results in [[1,2],[3,4]] . If the number of items in a doesn't split evenly, the last entry in a' will have all the rest. If n is greater than the number of items in the array (or is less than 0) it is clamped to the number of items in the array.

squash a -- a' (as of 22.07)

Reduces an "array of arrays" to a array whose contents are the contents of the arrays. Ex: [[1],[20]] a:squash returns [1,20] . If an item in the array is not itself an array, it is simply placed as-is.

switch a ix1 ix2 -- a (as of 22.05)

Swaps the items at the given array indices.

union a1 a1 w -- a3 (as of 22.02)

Creates an array a3 which is the union of two arrays over the comparator word. That means that the result contains all values in both inputs, excluding duplicates.

uniq a w -- a' (as of 22.02)

Removes consecutive equal elements of the array. w should return true if the items are equal. Assumes the input array is sorted.

unzip a -- a' (as of 22.05)

Inverse of a:zip . Takes an array like [[1,2], [3,4]] and produces [1,3,2,4] . Iterates over all the sub-arrays in the original, and creates a new array containing the corresponding elements of each sub-array, in the order given.


See also: a:zip
when a --

Given an array containing pairs of words, it invokes the first word in each pair. If that word evaluates to true , then the second word is invoked. If none of the elements evaluates to true , then if there is a last (unpaired) item it is invoked.


See also: a:when!
when! a --

Same as a:when , but invokes all words whose matching first part evaluates to true .


See also: a:when
x a1 a2 w -- a' (as of 18.08)

Same as a:x-each , but returns an array with the results from the processing. So w 's SED is n1 n2 x1 x2 -- x3 , where x3 is put in the resultant array. Modifying the arrays while it being iterated may throw an exception.


See also: a:x-each
x-each a1 a2 w -- a1 a2 (as of 18.08)

Iterate over two arrays, invoking w for all elements in them. The effect is to invoke w on every pair of items in the two inputs. w 's SED is: n1 n2 x1 x2 -- ; that is, it is passed the indices of both items, and the items themselves. The arrays are not available on the stack while it is running, to avoid consistency problems. w must consume its inputs. Will stop iterating on break or when all items have been iterated.

NOTE: You must not modify the array being iterated, while it is being iterated! Modifying the array while it is being iterated may throw an exception.


See also: a:each a:each! a:2each a:x
xchg a ix x -- a x' (as of 18.04)

Stores a new value in the array at index ix , placing the current value on TOS. A negative index means "from the end of the array".


See also: G:xchg m:xchg
y a w -- a'

Given an array and a word whose SED is x1 x2 -- x3 , produces another array which is the result of applying w to consecutive elements of it. This will result in an array one element shorter than the input. If the input has fewer than two elements, a clone will be returned and w will not be invoked.

zip a1 a2 -- a3 a4 ...

Takes two arrays, and "zips" them together (think like a "zipper" on clothing), producing a new array for each corresponding item in the first two. Ex: [1,2,3] [3,4,5] a:zip produce [1,3] [2,4] [3,5] . If the arrays are not of equal size, stops after processing the shorter one. Thus the number of resultant arrays will the minimum of the lengths of the two inputs.

Note: be careful not to use this on very long arrays or you may overflow the stack!

Astronomical

Namespace: astro
Description: Various astronomical calculations

word sed/description
dawn -- v
needs astro/sunrise

var with dawn angle of sun, v. Default is -7.

do-dawn -- rise set
needs astro/sunrise

Do dawn calculation.

do-dusk -- rise set
needs astro/sunrise

Do dusk calculation.

do-rise -- rise set
needs astro/sunrise

Do sunrise/sunset calculation (this is the default).

dusk -- v
needs astro/sunrise

var with dusk angle of sun, degrees below horizon. Default is -7.

latitude -- v
needs astro/sunrise

var with latitude coordinate of location (default is Jerusalem: 31.778). North is positive, south is negative.

location! loc -- lock
needs astro/sunrise

Takes a location map from the geo/location and sets current latitude and longitude.

longitude -- v
needs astro/sunrise

var with longitude coordinate of location (default is Jerusalem: 35.235). East is positive, west is negative.

sunrise d -- rise set
needs astro/sunrise

For the given date d, return rise, set times. Assumes the location has been set already.

Authentication

Namespace: auth
Description: Authentication for communication channels

word sed/description
genkeys -- priv pub (as of 22.06)
needs auth/keys

Return a pair of keys to be used for session authentication

secret priv pub -- b (as of 22.06)
needs auth/keys

Return a buffer which is the DH shared-secret of the keys

session-id -- s (as of 22.06)
needs auth/sessionkey

Return a random 16 character string (12 bytes of random data). This string is intended to identify the session from amongst a multitude of sessions over the channel. Save

session-key -- b (as of 22.06)
needs auth/sessionkey

Return a random session-key. A key is a cryptographically random buffer which can be used for encrypting the communications channel. The key should not be stored permanently.

validate priv pub key -- T (as of 22.06)
needs auth/keys

With one party's public key and the other party's private key, validate that the 'key' is the result of 'auth:secret'

AWS

Namespace: AWS
Description: Amazon AWS CLI utility

word sed/description
cb w -- (as of 23.03)
needs amazon/aws

Set the given word as the callback for AWS:cmd to use (if the cb was null ; otherwise, use the cb given). The default callback sets the value returned by AWS:rc , which will contain the last return code from any AWS command. If you do multi-task AWS operations, this is probably not sufficient.

cli s -- (as of 23.03)
needs amazon/aws

Set the aws CLI command string. The default is just aws , but you may need to provide a full path name.

cmd cmd [opts] cb -- (as of 23.03)
needs amazon/aws

Execute the given command and options, asynchronously shelling the aws CLI utility (which you must have installed on your system)

cp args cb -- (as of 23.03)
needs amazon/aws

Issue the AWS CLI cp command to copy files to and from your AWS bucket.

rc -- n (as of 23.03)
needs amazon/aws

Returns the last return-code returned from an AWS operation (unless you used AWS:cb , in which case it's on you).

Blockchain

Namespace: bc
Description: Blockchain Framework

word sed/description
+block chain x -- chain
needs blockchain/framework

Create a new block containing the string or buffer data item x and add it to the given chain

.blocks chain -- chain
needs blockchain/framework

Prints the blocks in the given blockchain

add-block chain block -- chain
needs blockchain/framework

Internal word which adds the given block to the chain. You will use bc:+block instead

block-hash block -- block hash
needs blockchain/framework

Calculates the hash for the given block, assuming the values it contains are correct

block@ chain ix -- chain block
needs blockchain/framework

Given a chain and a number block index, return the block. Return null if there is no such block. In future will accept the hash

first-block -- block
needs blockchain/framework

Returns the first, or "genesis" block for the chain. NOTE: currently, all genesis blocks are identical

hash -- v
needs blockchain/framework

A global var which contains the name of the hash to be used. By default, this is 'blake'. NOTE: if you are using blockchains and you also need to use other hash algos, you should either make certain to save and restore the hash in your non-blockchain code, or ensure the blockchain code runs on a separate task (e.g. thread)

last-block chain -- chain block
needs blockchain/framework

Returns the last block in the chain

load chain file -- chain flag
needs blockchain/framework

Loads a BC_MEM blockchain from a file, where it was saved previously with bc:save

new -- chain
needs blockchain/framework

Sets the hash to use and initializes the blockchain. Returns a new and empty blockchain to use. The blockchain is set initially to be "in-memory". NOTE: a blockchain should not be shared between tasks, since the hash algo it sets is task-specific

save chain file -- chain flag
needs blockchain/framework

For a BC_MEM blockchain, saves it to a file, so it may be restored with bc:load

set-sql chain file-name -- chain flag
needs blockchain/framework

Sets the chain to be a BC_SQL chain. If file-name doesn't exist, a new SQL file is created and the chain initialised. Otherwise, the chain is loaded from the file. If the file exists but is not a valid SQL file or doesn't contain a valid chain, false is returned on TOS; otherwise, true is returned.

validate chain -- chain flag
needs blockchain/framework

Validate that the entire chain is valid

validate-block chain block -- chain block flag
needs blockchain/framework

Validate that the block's hash is valid, and that its prior hash is the previous block's hash

Bloom filters

Namespace: bloom
Description: Bloom filters

word sed/description
add filter value -- filter
needs utils/bloomfilter

Adds the string value to the Bloom filter

filter size #hash -- filter
needs utils/bloomfilter

Create a new Bloom filter, which can have up to size items, using #hash different hashes.

in? filter value -- filter flag
needs utils/bloomfilter

Checks if the string value is in the Bloom filter. If it returns false, the value is definitely not in the filter. Otherwise, depending on the filter parameters, it is probably in it.

Bluetooth

Namespace: bt
Description: Bluetooth discovery and I/O

word sed/description
accept bt -- bt'
Professional version

Given a bt created with bt:listen , waits for a connection to be created. When it is, returns bt2 which can be used with bt:read and bt:write . Returns null if there was an error.


See also: bt:listen bt:read bt:write
ch! bt svcuuid uuid b -- bt T (as of 16.11)
Professional version

Writes a BLE characteristic identified by the string uuid in the service identified by the string svcuuid on the BT connection given in bt . The buffer will be written; you must ensure that it contains data appropriate for the service and characteristic. Returns true if it succeeded initiating the write, false otherwise.

NOTE: Currently unimplemented as of 20.01


See also: bt:ch@
ch@ bt svcuuid uuid -- bt b (as of 16.11)
Professional version

Reads a BLE characteristic identified by the string uuid in the service identified by the string svcuuid on the BT connection given in bt . A buffer will be returned (or null if it was unable to read).

NOTE: Currently unimplemented as of 20.01


See also: bt:ch!
connect m -- bt
Professional version

Given a map representing information about a BT device, as returned from bt:scan , returns a new bt which may be used with bt:read and bt:write . If it fails to connect, returns null .

Additional keys in m may be:

  • "l2cap": optional; if true use L2CAP protocol, otherwise use RFCOMM (the default)
  • "port" - a number defining the port to use
  • "uuid" - a string containing the UUID of the service to connect to

See also: bt:scan bt:read bt:write
disconnect bt -- bt (as of 16.12)
Professional version

Given a bt returned from bt:connect or bt:leconnect , disconnect the connection (if the bt is currently connected).

init -- T (as of 19.09)

Ensures the Bluetooth system is running; returns false if not.

leconnect m -- bt (as of 16.11)
Professional version

Given a map returned from bt:lescan , returns a new bt which may be used with bt:read and bt:write . If it fails to connect, returns null .


See also: bt:lescan bt:read bt:write
lescan w n -- (as of 16.11)
Professional version

Scans for nearby Bluetooth Low Energy (BLE) devices. w is invoked for any devices found. Its SED is: m -- T , where m has information about the device found, and the return value is true to continue scanning or false to stop scanning.

The scan will continue as long as any devices were found within n seconds. If no devices were found within n seconds, the scan will cease and w will be invoked with a parameter of null . w is invoked on a separate task (thread) and should not do more than save the information and set a flag or similar.

listen m -- bt
Professional version

Given a map defining what service to bind to and listen on etc., returns a new bt item which may be used with bt:accept . If it fails to connect, returns null .

The keys in m are:

  • "l2cap" - optional; if true use L2CAP protocol, otherwise use RFCOMM (default RFCOMM)
  • "port" - a number defining the port to use
  • "uuid" - a string containing the UUID of the service to publish

See also: bt:accept
on? -- T (as of 16.11)
Professional version

Returns true if the Bluetooth system of the machine is on, false otherwise.

read bt s n -- bt s n
Professional version

Same as f:read but for a bt connection.


See also: bt:write bt:connect
scan w n --
Professional version

Scans for nearby Bluetooth (BT) devices for n seconds. The word w is invoked for each device found, and has the SED: m -- T , where m is a map with the device information. It is passed null when the scan is done. It must return true to continue scanning, or false to terminate the scan.

The map passed to w for each device will contain the keys "id" and "name", where "id" is the 48-bit identifier and "name" is the friendly name given the device by its owner.

service? s uuid -- a|null
Professional version

Scans the BT device with string identifier s (as returned from bt:scan ) for services using the string UUID (or null for all services). Returns an array of service descriptors or null if none are available.

services? bt w n -- bt (as of 16.11)
Professional version

Takes a bt returned from bt:leconnect representing a BLE peripheral, and invokes w for each service the peripheral advertises. n is a timeout value in seconds for the service scan to complete.

Implemented on Android, iOS, and macOS.

write bt s -- bt n
Professional version

Same as f:write but for a bt connection.


See also: bt:read bt:connect

BSON

Namespace: bson
Description: BSON parse

word sed/description
parse b w -- (as of 23.06)

Parse a buffer of BSON data, invoking the callback w after each document (map or array). The SED of w is x -- T where x is a map or array parsed from the BSON (as a "document"), and the return value is true to continue or false to stop. If there is an error in parsing, null is passed to the callback, and t:err? explains the problem.

Buffer

Namespace: b
Description: Buffers represent a memory area with a specific length

word sed/description
! b ix n -- b'

Put the byte n at offset ix in the buffer. If you wish to modify the original buffer, you must invoke b:writable on it first.


See also: b:@ b:writable
+ b1 b2 -- b3

Appends the buffer b2 to the buffer b1 yielding a new buffer.

/ b n -- a | b a1 -- a2

Split the buffer b at n , returning a two-element array [head, tail] . If n is negative, splits b from the end rather than at the start.

If an array of numbers a1 is given, then it returns an array containing buffers which represent the original b split at the sizes (not offsets) indicated. Ex: splitting a buffer with 20 bytes using [1,2] will give a three-element array with the first byte, then the next two bytes, with the remainder of 7 bytes in the last element.


See also: s:/
1+ b ix -- b (as of 19.09)

Add 1 to the byte at offset ix in the buffer. Modifies b , so it must be writable.

1- b ix -- b (as of 19.09)

Subtract 1 from the byte at offset ix in the buffer. Modifies b , so it must be writable.

<> b ix1 ix2 -- b (as of 22.07)

Swaps the bytes at those indices in the buffer. Does modify the original buffer! If you don't want to modify the original, take care to clone it first.

= b1 b2 -- T

Compare the two buffers, returning true if they are byte-wise equal.

>base16 sb -- s (as of 21.02)
Professional version

Takes a string or buffer and converts it to a RFC-4648 base16 encoded string

>base32 sb -- s (as of 21.02)
Professional version

Takes a string or buffer and converts it to a RFC-4648 base32 encoded string

>base64 b -- s

Encode buffer (or string) in base64 encoding.


See also: b:base64>
>base85 sb -- s (as of 21.02)
Professional version

Takes a string or buffer and converts it to a RFC-4648 base85 encoded string

>hex s -- b

Convert the 'hex dump' string into the bytes it represents.


See also: b:hex>
>mpack x -- b T (as of 18.08)
Professional version

Converts any 8th item to a buffer containing the equivalent MessagePack binary format. TOS is true if the conversion succeeded, false otherwise.

@ b ix -- b n

Returns the byte at offset ix in the buffer. Returns null if the offset is beyond the bounds of the buffer.


See also: b:!
append b1 b2 -- b1 (as of 17.10)

Appends the buffer or string b2 to the buffer b1 , modifying the original buffer.

base16> s -- b (as of 21.02)
Professional version

Takes a string encoded in RFC-4648 base16 and returns a decoded buffer.

base32> s -- b (as of 21.02)
Professional version

Takes a string encoded in RFC-4648 base32 and returns a decoded buffer.

base64> s -- b

Decode string s from base64 encoding into a buffer.


See also: b:>base64
base85> s -- b (as of 21.02)
Professional version

Takes a string encoded in RFC-4648 base85 and returns a decoded buffer.

bit! b ix n -- b (as of 18.04)

Sets the value of the bit at the given index to n , where position 0 is the low bit of the first byte in the buffer. ix must be within the bounds of b . n is evaluated as 1 if true , or 0 otherwise.

Modifies b , so it must be writable!

bit@ b ix -- b n (as of 18.04)

Gets the value of the bit at the given index in the buffer, treating it as an array of bits. Position 0 is the low bit of the first byte. Returns null if n is beyond the bounds of b .


See also: b:bit!
clear b -- b

Overwrites the contents of the b with 0.

Note: this modifies the original buffer itself!


See also: s:clear
compress b -- b'

Exactly analogous to s:compress .


See also: s:compress b:expand
conv b from to -- b' | b from to -- n null (as of 16.05)

Converts the buffer from the character encoding from to to , returning a converted buffer. If it was unable to perform the conversion, returns an error code and null .

Note: Linux and RPI users must have installed the "libiconv" library for this to work. The errcode (if null was returned) is one of:

  • 1 : no libiconv library
  • 2 : unknown charset
  • 3 : error converting text
each b w -- (as of 16.02)

Invokes w for each byte of the buffer. The SED of w is: ix n -- , where ix is the index of the byte in the buffer and n is the value of the byte at that index. The original buffer is not present on the stack while this word is running.

each! b w -- (as of 19.04)

Same as b:each , but only passes the byte value, omitting the index item, to the word. The SED of w is: n -- .


See also: b:each
each-slice b n w -- (as of 17.04)

Invokes w for each slice n bytes wide of the buffer. It is w 's responsibility to consume the buffer. The SED of w is: ix b -- , where the ix is the index of the slice in the b , and b is the slice of b at ix times n bytes in the original. Each slice is n wide, with the possible exception of the last one.

expand b n -- b'

Exactly analogous to s:expand .


See also: s:expand b:compress
fill b n -- b' | b ix sb -- b'

Fills the contents of the b with the Unicode character n , or fill it with the contents of the string or buffer sb starting at offset ix in b .

Note: if you want to modify the original buffer, you must use b:writeable to permit that; otherwise, a new buffer is created.


See also: s:fill
getb buf -- buf b
needs buf/getb

Read a single byte from the given buffer. If no byte is available, null is returned.

hex> b -- s (as of 16.11)

Converts a buffer into its "hex dump" representation.


See also: b:>hex
len b -- b n

Returns the length of the buffer in bytes.

mem> n size -- b (as of 17.01)

DANGEROUS! Returns a buffer containing a copy of the contents of the memory at address n for size bytes.

Note: if you give an invalid memory address and/or size, you may cause 8th to crash. Also, if you allow arbitrary code to access this word, you open a security hole, so use "w:forget" or "G:only" if you allow arbitrary code to be evaluated.

move b dst src n -- b (as of 18.01)

Moves n bytes of the buf from src to dst . The original buf is modified!

mpack-compat T -- (as of 20.08)
Professional version

By default, the mpack words add a compatibility tag to all future versions of 8th to unpack older versions. However, that means 8th's packing is not decipherable to third-party programs. To make the encoding acceptable to outsiders, pass true to this word.

mpack-date T -- (as of 18.08)
Professional version

If true , then the b:>mpack word will convert a date into the MessagePack date extension format. This loses timezone information, but is necessary if you interoperate with 3rd-party software using standard MessagePack. The default is false , which means that date information will round-trip correctly between 8th instances. This only affects serialization; b:mpack> will still deserialize date data sent in 8th format, as well as MessagePack format.

mpack-ignore T -- (as of 18.08)
Professional version

If true , the b:mpack> word will ignore any extended types it doesn't know about. The default is false , which causes an error on unknown extended types.

mpack> b -- x flag (as of 18.08)
Professional version

Converts a buffer containing MessagePack binary data into the appropriate 8th item. Returns true and the item if successful, or false and null on failure to convert.

n! b ix n T n' -- b (as of 21.06)

Inverse of b:n@ . Stores the number n' at the byte-offset ix in the buffer. The bits value n is one of 1,2,4 or 8.

Modifies b , so requires the buffer be writable, otherwise does nothing.


See also: b:n@
n+ b ix n -- b (as of 19.09)

Adds the number to the byte at offset ix in the buffer. Modifies b , so it must be writable.

n@ b ix n T -- b n' (as of 21.06)

Gets values from the buffer as numbers of byte-size n , a byte-offset ix . If T is true , treat the number as signed, otherwise unsigned. n must be one of '1', '2', '4', or '8'.

Ex: 2 2 true b:n@ will get a signed 16-bit number from byte-offset 2 in the buffer.

If the index+bittedness is out of range of the buffer, null is returned.


See also: b:n!
new x -- b

Create a new buffer. If x is a:

  • number: create a buffer of size x bytes which is NOT initialized (use b:clear or b:fill to do that)
  • string: create a buffer as big as the contents of the string, with a copy of the string's contents
  • buffer: create a clone of the original one
  • array of numbers: create a buffer containing the byte-values of the numbers in the array (one byte per number only).
op source key w -- b

Takes two buffers and invokes the word w for each byte of source , and a corresponding byte from key (modulo the size of key ). The resultant byte goes into the corresponding byte of b .

This can be used, for example, to perform an "xor" of a password against a block of data. The result is a buffer the same size as source .

The SED of w is: n1 n2 -- n3 , where n1 is a byte from source , and n2 is a corresponding byte from key .

op! b ix w -- b (as of 22.03)

Invokes w on the byte at offset ix in the buffer, which must be writable. The SED of w is n -- n , the resultant value is placed back in b at offset ix .

pad b len -- b' (as of 20.05)
needs buf/pad

Pad the given buffer to a multiple of 'len' bytes, using the number of bytes as the filler. Always pads the buffer, even if it is already a multiple of 'len' Can only use a 'len' up to 0xFF


See also: b:unpad
rev b -- b' (as of 16.04)

Reverses the order of bytes in a buffer.

search haystack needle -- haystack n | haystack ofs needle -- haystack n

Search the buffer haystack for the first occurrence of the string or regex or number needle , returning the numeric offset in the buffer of the found data, or null . If ofs is given it's a number of bytes to search from the start of the buffer. If needle is a number, the lowest byte of it is searched for (e.g. it's treated as a "uint8_t").


See also: s:search
shmem s n T -- b

Returns a buffer containing "shared memory", given a string to use as an identifier for an IPC shared-memory object, a number specifying its size, and a boolean indicating if the memory should be read-only (if true ). Returns null if this was not possible.

slice b1 ix n -- b2

Returns a slice of the buffer b1 , semantically the same as s:slice . b2 is a "slice" of b1 , beginning at offset ix for n bytes (not characters!). A negative value of n means "take the rest of the buffer".


See also: s:slice
splice b1 b2 ix -- b' (as of 19.01)

Replaces a portion of the buffer b1 starting at offset ix with the contents of the buffer b2 . If b1 is writable, then b1 itself is modified and returned.

ungetb buf b -- buf
needs buf/getb

Take the given byte and "unget" it, so that the next b:getb will return it.

unpad b -- b' (as of 20.05)
needs buf/pad

Undoes the padding done by b:pad. Do not use it on a buffer which was not padded!


See also: b:pad
writable b T -- b (as of 17.01)

Make the buffer writable if T is true . Normally, attempting to modify a buffer will return a modified clone of the original. This allows modifying the original. Use with caution!.


See also: b:!
xor b n -- b' | b1 b2 -- b' (as of 16.02)

Applies a byte-wise XOR between every byte of the buffer and either the Unicode character or the buffer b2 . Repeats until every byte of the input buffer has been XORed.

Note: if the original buffer is writable, its contents are overwritten; otherwise, a new buffer is created.

calendar

Namespace: cal
Description: Calendar utilities

word sed/description
(.hebrew) month day year -- S
needs calendar/hebrew

Returns a string with the given Hebrew date.

(.islamic) year month day -- s
needs calendar/islamic

Returns a string corresponding to the Islamic date given.

.hebrew month day year --
needs calendar/hebrew

Prints the given Hebrew date.

.islamic year month day --
needs calendar/islamic

Prints the Islamic date given.

>hebepoch gy -- hy
needs calendar/hebrew

Convert Gregorian year gy to Hebrew year hy.

>jdn d -- n (as of 20.01)
needs calendar/julian

Converts a date to a "Julian day number" as used in astronomy


See also: cal:jdn>
Adar -- 12
needs calendar/hebrew

Constant representing the twelvth Hebrew month.

Adar2 -- 13
needs calendar/hebrew

Constant representing the thirteenth Hebrew month, in a leap year.

Av -- 5
needs calendar/hebrew

Constant representing the fifth Hebrew month.

Elul -- 6
needs calendar/hebrew

Constant representing the sixth Hebrew month.

Heshvan -- 8
needs calendar/hebrew

Constant representing the eighth Hebrew month.

Iyar -- 2
needs calendar/hebrew

Constant representing the second Hebrew month.

Kislev -- 9
needs calendar/hebrew

Constant representing the ninth Hebrew month.

Nissan -- 1
needs calendar/hebrew

Constant representing the first Hebrew month.

Shevat -- 11
needs calendar/hebrew

Constant representing the eleventh Hebrew month.

Sivan -- 3
needs calendar/hebrew

Constant representing the third Hebrew month.

Tammuz -- 4
needs calendar/hebrew

Constant representing the fourth Hebrew month.

Tevet -- 10
needs calendar/hebrew

Constant representing the tenth Hebrew month.

Tishrei -- 7
needs calendar/hebrew

Constant representing the seventh Hebrew month.

days-in-hebrew-year hyr -- days
needs calendar/hebrew

How many days are in the given year?.

displaying-hebrew -- v
needs calendar/hebrew

A var which controls whether the Hebrew date displays in Hebrew or English. Defaults to false.

fixed>hebrew date -- month day year
needs calendar/hebrew

Converts the fixed-date into the Hebrew date.

fixed>islamic fixed -- year month day
needs calendar/islamic

Convert the given fixed-date to the Islamic date.

gershayim s -- s2
needs calendar/hebrew

Inserts the Hebrew "gershayim" character (0x05f4) as appropriate for a Hebrew number.

hanukkah hy -- fixed
needs calendar/hebrew

Returns the fixed-date of the first day of Hanukkah in the given Hebrew year.

hebrew-epoch -- hepoch
needs calendar/hebrew

Fixed date corresponding to the beginning of AM (anno mundi, Hebrew year).

hebrew-leap-year? yr -- flag
needs calendar/hebrew

Return 1 if yr is a Hebrew leap year or 0 otherwise.

hebrew>fixed month day year -- date
needs calendar/hebrew

Convert the Hebrew month, day and year given into a "fixed date", a number.

hebrewtoday -- month day year
needs calendar/hebrew

Returns a the Hebrew date corresponding to today.

hmonth-name nr -- s
needs calendar/hebrew

Returns a string containing the name of the Hebrew month given as a number. Returns Hebrew if d:displaying-hebrew is true.

islamic.epoch -- epoch
needs calendar/islamic

Returns the fixed-date of the start of the Islamic epoch.

islamic>fixed year month day -- fixed
needs calendar/islamic

Convert the given Islamic date to a fixed-date.

islamictoday -- year month day
needs calendar/islamic

Returns the Islamic date corresponding to today.

jdn> n -- d (as of 20.01)
needs calendar/julian

Converts a "Julian day number" as used in astronomy to a date


See also: cal:>jdn
last-day-of-hebrew-month month year -- day
needs calendar/hebrew

Returns the last day of the given month in a particular year. Either 29 or 30, takes into account the dehiyot etc.

number>hebrew n -- s
needs calendar/hebrew

Returns a string which is the traditional Hebrew number corresponding to the number given.

omer hy -- days
needs calendar/hebrew

Returns the "count of the omer" for the specific fixed-date. If that date is outside the omer period, returns 0.

pesach hy -- fd
needs calendar/hebrew

Returns the fixed-date of Passover in the given Hebrew year.

purim hy -- fd
needs calendar/hebrew

Returns the fixed-date of Purim in the given Hebrew year.

rosh-chodesh? fd -- flag
needs calendar/hebrew

Returns true if the given fixed-date is "Rosh Chodesh".

rosh-hashanah hy -- fd
needs calendar/hebrew

Returns the fixed-date of Rosh Hashana in the given Hebrew year.

shavuot hy -- fd
needs calendar/hebrew

Returns the fixed-date of Shavuot in the given Hebrew year.

taanit-esther hy -- fixed
needs calendar/hebrew

Returns the fixed-date of the Fast of Esther in the given Hebrew year.

tisha-beav hy -- fixed
needs calendar/hebrew

Returns the fixed-date of the Fast of the Ninth of Av in the given Hebrew year.

yom-haatsmaut hy -- fixed
needs calendar/hebrew

Returns the fixed-date of the Israeli Independence Day in the given Hebrew year.

yom-kippur hy -- fd
needs calendar/hebrew

Returns the fixed-date of Yom Kippur in the given Hebrew year.

Colors

Namespace: clr
Description: Colors

word sed/description
>hsva x -- a (as of 24.04)

Returns the color converted from ARGB to HSVA as an array [hue,saturation,value,alpha].

complement x -- n (as of 24.04)

Returns a color "complimentary" to the given one.

dist x1 x2 -- n (as of 24.04)

Returns the "distance" between two colors, a value between 0 and 1 where 0 means identical.

gradient x1 x2 n -- a (as of 24.04)

Returns a gradient of colors from x1 to x2, in n steps.

hsva> a -- n (as of 24.04)

Inverse of clr:>hsva . Takes an array of HSVA and returns the RGBA value.

invert x -- n (as of 24.04)

"inverts" the given color

nearest-name x -- s (as of 24.04)
needs nk/color

Takes a color name or value, and returns the name of the color most nearly matching it from our internal list of colors.

parse x -- n (as of 24.04)

Converts a color definition (number, string, or array of values) to an RGBA number value of the color.

Complex

Namespace: c
Description: Numbers: complex (native doubles)

word sed/description
* c1 c2 -- c3 (as of 18.07)

Multiplies two complex numbers.


See also: c:new c:+ c:abs c:>ri c:conj c:arg c:=
* c1 c2 -- c3
needs math/complex

Returns the complex product of the two inputs.

+ c1 c2 -- c3
needs math/complex

Adds two complex numbers returning their complex sum.

+ c1 c2 -- c3 (as of 18.07)

Adds two complex numbers.


See also: c:new c:* c:abs c:>ri c:conj c:arg c:=
= c1 c2 -- T
needs math/complex

Compares two complex numbers and returns true if they are equal.

= c1 c2 -- T (as of 18.07)

Compares two complex numbers, returning true if they are equal.


See also: c:new c:+ c:* c:>abs c:>ri c:conj c:arg
>polar c -- c' (as of 24.04)
needs math/complex

Returns the complex number in "polar form"

>polar c -- c' (as of 24.04)

Returns the complex number in "polar form".

>ri c -- real imag
needs math/complex

Returns the "real" and "imaginary" components of the complex number.

>ri c1 -- real imag (as of 18.07)

Returns the "real" and "imaginary" components of the complex number.


See also: c:new c:+ c:* c:>abs c:conj c:arg c:=
^ c n -- c' (as of 24.04)
needs math/complex

Raises the complex number c to the exponent n, analagous to n:^ .

^ c n -- c' (as of 24.04)

Raises the complex number c to the exponent n, analagous to n:^ .

abs c -- n
needs math/complex

Returns a the absolute-value (e.g. magnitude) of the input.

abs c1 -- n (as of 18.07)

Returns the absolute-value of the complex number.


See also: c:new c:+ c:* c:>ri c:conj c:arg c:=
arg c -- n
needs math/complex

Returns the "argument" (e.g. angle of the radius, in radians) of the input.

arg c -- n (as of 18.07)

Returns the "argument" (the angle of the radius in radians) of the complex number.


See also: c:new c:+ c:* c:>abs c:>ri c:conj c:=
conj c -- c'
needs math/complex

Returns the "complex conjugate" of the input. If c is 1+2i, c' is 1-2i.

conj c -- c' (as of 18.07)

Returns the complex-conjugate of the complex number.


See also: c:new c:+ c:* c:>abs c:>ri c:arg c:=
im c -- im
needs math/complex

Returns a number which is the "imaginary" component of the complex number c.

im c -- n (as of 24.04)

Returns the imaginary component of the complex

log c -- c' (as of 24.04)
needs math/complex

Returns the "principal value" of the natural logarithm of c .

log c -- c' (as of 24.04)

Returns the "principal value" of the natural logarithm of c .

n> n -- c (as of 24.04)

Converts a number to a complex, e.g. creates a new complex number, n + 0i

n> n -- c
needs math/complex

Converts a number to the complex c, represented as "n+0i".

new real imag -- c | a -- c (as of 18.07)

Create a new complex number based on native doubles (not regular 8th numbers). This is a faster implementation than the one in the "math/complex" library, but it does not allow unlimited precision.

The parameters are either two numbers or an array of two numbers, in the order "real, imag". The numbers given must fit into a native double or they will be truncated, with unpredictable results. May return null if inappropriate values are given.


See also: c:+ c:* c:abs c:>ri c:conj c:arg c:=
new a -- c
needs math/complex

From either a pair of numbers, or an array containing two numbers, returns a new complex representing "real + i * imag".

polar> n1 n2 -- c (as of 24.04)
needs math/complex

Returns the complex number determined by the "polar coordinates" n1 (abs(c)), and n2 (arg(c)).

polar> n1 n2 -- c (as of 24.04)

Returns the complex number determined by the "polar coordinates" n1 (abs(c)), and n2 (arg(c)).

re c -- re
needs math/complex

Returns a number which is the "real" component of the complex number c.

re c -- n (as of 24.04)

Returns the real component of the complex

Console

Namespace: con
Description: Console I/O

word sed/description
>redir --
needs console/redirect

Redirects console output (from "." etc) to a string

accept n a -- s

Requests a string of maximum length n from the console (a length of 0 implies maximum, which is 4096 characters). If desired, a history array of strings may be provided (or null if no history is needed). The same editing keys as with regular console input are allowed. Returns the entered string or null if Ctrl+C was pressed.


See also: meta:console con:key con:accept-pwd
accept-nl T -- (as of 23.03)

If false , con:accept will not print an initial newline. The default is true .

accept-pwd n -- s

Same as con:accept , except it does not display the characters entered. Instead, it shows '*' for each character. The same editing keys are allowed as with con:accept .


See also: con:accept con:key
alert -- (as of 22.05)
IMMEDIATE

Invoked from the 'con:accept' words if an 'alert' is required. The default does nothing.

ansi? -- T (as of 20.05)

Returns true if the console supports ANSI sequences. Only relevant on Windows.

black --
needs console/loaded

Set the console foreground color to black. Must be paired with one of the con:on... color commands.

blue --
needs console/loaded

Set the console foreground color to blue. Must be paired with one of the con:on... color commands.

clreol --

Clear the current console line from the current position until the end of the line.


See also: meta:console con:cls
cls --

Clear the console screen and put the cursor on the first row.


See also: meta:console con:clreol
ctrld-empty T -- (as of 23.07)

If T is true , make the REPL only quit on Ctrl+D if the input buffer is empty. The default is false , meaning always quit when Ctrl+D is pressed.

cyan --
needs console/loaded

Set the console foreground color to cyan. Must be paired with one of the con:on... color commands.

down --

Move the console position down one.


See also: meta:console con:left con:right con:up
file>history T s -- (as of 22.03)
needs console/history

Restore console history from a file. If T is true , overwrites current history; otherwise, appends to it.

free --

Closes the console window.

Note: Windows OS only.

getxy -- row col

Returns the position of the console cursor.

gotoxy row col --

Set the console cursor position.


See also: meta:console con:getxy
green --
needs console/loaded

Set the console foreground color to green. Must be paired with one of the con:on... color commands.

history-handler w -- (as of 22.03)
needs console/history

Set the history handling word. Its SED is s -- . The default handler saves to the file given in con:history>file , and runs in the REPL task. You can do other things if you like

history>file s -- (as of 22.03)
needs console/history

Save console history to the named file, one line per item. If null is given, stop saving history. If the file name cannot be created or opened, history will not be saved.

init -- T (as of 24.01)

Returns true if the console subsystem could be initialized; otherwise returns false and sets t:err? .

key -- n

Returns the key-code of a pressed key, waiting for a key to be pressed.


See also: meta:console con:key? con:accept con:accept-pwd
key? -- T

Returns true if con:key would return a value without blocking, false otherwise.


See also: con:key meta:console
left --

Move the console position left one.


See also: meta:console con:right con:up con:down
load-history a T --

Load the console's history from the array of strings. If T is true , overwrite the current history; otherwise, append the array's contents to the current history.


See also: meta:console
magenta --
needs console/loaded

Set the console foreground color to magenta. Must be paired with one of the con:on... color commands.

max-history n -- (as of 23.03)

Changes the default console history size from 100 to n . The maximum is 100000.


See also: meta:console
onBlack --
needs console/loaded

Set the console background color to black.

onBlue --
needs console/loaded

Set the console background color to blue.

onCyan --
needs console/loaded

Set the console background color to cyan.

onGreen --
needs console/loaded

Set the console background color to green.

onMagenta --
needs console/loaded

Set the console background color to magenta.

onRed --
needs console/loaded

Set the console background color to red.

onWhite --
needs console/loaded

Set the console background color to white.

onYellow --
needs console/loaded

Set the console background color to yellow.

print s --

Print the string to the console, taking into account console text attributes and positioning.


See also: meta:console
red --
needs console/loaded

Set the console foreground color to red. Must be paired with one of the con:on... color commands.

redir> -- s
needs console/redirect

Stops console redirection and returns the captured string

redir? -- T

Returns true if the input is redirected (from a pipe for instance).


See also: meta:console
right --

Move the console position right one.


See also: meta:console con:left con:up con:down
save-history w -- | null --

If given word, it is a callback for saving history whose SED is s -- . If null , stop saving history.

History is not saved by default. This word causes the history to be saved from the point it is invoked with a word, until the point it is invoked with null .

The library console/history implements history saving in a more easy-to-use manner.


See also: meta:console
size? -- col row (as of 16.10)

Returns the current size of the console in columns and rows.

up --

Move the console position up one.


See also: meta:console con:left con:right con:down
white --
needs console/loaded

Set the console foreground color to white. Must be paired with one of the con:on... color commands.

yellow --
needs console/loaded

Set the console foreground color to yellow. Must be paired with one of the con:on... color commands.

Crypto

Namespace: cr
Description: Encryption and decryption

word sed/description
>aes128gcm item key -- buf
needs crypto/aes128gcm

Encrypt the buffer or string item with the buffer or string key using AES-128-GCM. The key will be converted into an appropriate buffer using cr:ensurekey. The encrypted buffer buf is returned.

>aes256gcm sb sb2 -- b (as of 17.04)

Encrypts sb using AES-256-GCM using the key sb2 returning a buffer which can be decrypted with cr:aes256gcm> . If sb2 is not a 32-byte buffer, it will be converted to one using cr:ensurekey .


See also: cr:aes256gcm> cr:ensurekey
>cp sb sb2 -- b (as of 17.04)

Takes a string or buffer sb , and a string or buffer key sb2 , encrypts using Chacha20Poly1305, returns a buffer which can be decrypted with cr:cp> . If sb2 is not a 32-byte buffer, it will be converted to one using cr:ensurekey .


See also: cr:cp> cr:ensurekey
>cpe sb b b2 -- b3 (as of 17.04)

Encrypts the string or buffer using the key b with Chacha20Poly1305, signs with the private Ed25519 key b2 , then boxes it up in a buffer b3 . That can be given to cr:cpe> to verify and decrypt.


See also: cr:cpe>
>decrypt sb key -- cr | sb key iv aad tag -- cr | m -- cr

Given a buffer key containing an encryption key (see cr:genkey or cr:randkey ) and a string or buffer with encrypted data, begins decryption and returns a crypt which must be passed to further crypt words, or null if there was an error. In GCM or "chacha1305" modes, the iv, add, and tag are also required.

If a map is given, it has the same keys as for cr:>encrypt .


See also: cr:decrypt> cr:decrypt+
>edbox sb b -- b2 (as of 17.04)

Creates a "box" from a string or buffer s and an Ed25519 private key b (created using cr:ed25519 ), containing a header and the signature for the item and key.


See also: cr:edbox> cr:ed25519
>encrypt sb key -- cr | sb key iv aad -- cr | m -- cr

Given a buffer key containing an encryption key (see cr:genkey or cr:randkey ) and a string or buffer sb with data to encrypt, starts encryption and returns a crypt which must be passed to further crypt words, or null if there was an error.

In modes other than ECB, and for the "chacha" and "chacha1305" ciphers, a buffer iv must be given. In GCM mode or with the "chacha1305" cipher, a buffer aad may be given (or null must be passed, if no additional data is to be given). With the "chacha" cipher, the aad must be a number, used as a counter.

If a map is given, then its keys are as follows:

key kind description
key sb encryption/decryption key
tag b GCM etc tag
iv b IV
aad sb additional authentication data
read w callback word for getting input
write w callback word for writing output

The callback words, if present, have the following SEDs:

  • read: -- m b
>nbuf num -- buf
needs crypto/totp

Convert a number into a (64-bit) buffer of the binary digits.

>rsabox sb b -- b' (as of 17.04)

Creates a box containing a head and signature from the string or buffer sb and an RSA private key b (created using 64 cr:rsa_genkey ).


See also: cr:rsabox> cr:rsa_genkey
>uuid b -- s

Creates a UUID string from a 16-byte buffer.

aad? -- T (as of 17.04)

Returns true if the current crypto settings accept "additional authentication data".

aes128box-sig item key -- buf
needs crypto/aes128gcm

This is the encryption header, which identifies the 'box' as being AES128GCM. The last three numbers are "id", "IV size", and "tag length" (in AEAD suites).

aes128gcm> buf key -- item flag
needs crypto/aes128gcm

Inverse of cr:>aes128gcm. Decrypt the buffer buf with the buffer or string key using AES-128-GCM. The key will be converted into an appropriate buffer using cr:ensurekey. The decrypted buffer item is returned and flag is true, if the decryption was successful. Otherwise, the original buffer is returned and false is on TOS.

aes256box-sig -- b (as of 17.04)

Returns a buffer containing the correct 8-byte signature for an AES-256-GCM box.

aes256gcm> b b2 -- b' (as of 17.04)

Decrypts a buffer which was encrypted with cr:>aes256gcm , using the key buffer b2 . Returns null if the decryption failed.


See also: cr:>aes256gcm
aesgcm -- (as of 17.04)

Sets the encryption mode to GCM, the cipher to AES, and the GCM tag size to 16.

blakehash -- (as of 17.04)

Sets the current hash to "blake".

chacha20box-sig -- b (as of 17.04)

Returns a buffer containing the correct 8-byte signature for a Chacha20Poly1305 box.

chachapoly -- (as of 17.04)

Sets the current encryption cipher to "Chacha20Poly1305".

cipher! s -- (as of 16.01)

Set the cipher to use in this task. The string may be any of the ones returned by cr:ciphers . Throws an exception if given an unknown cipher name. The default value is "aes256-gcm".


See also: cr:hash! cr:encrypt cr:decrypt
cipher@ -- s (as of 16.04)

Returns the current cipher algorithm name, suitable for passing to cr:cipher! .


See also: cr:cipher!
ciphers -- a (as of 22.04)

Returns an array of the names of all supported ciphers.

cp> b b2 -- b' (as of 17.04)

Decrypts a buffer which was encrypted with cr:>cp , and a buffer key b2 which was used to encrypt it. Returns a buffer with the clear-text, or null if the decryption failed.


See also: cr:>cp cr:ensurekey
cpe> b b2 b3 -- b' (as of 17.04)

Decrypts the buffer b created by cr:>cpe , using the key b2 and verifying with the public Ed25519 key b3 . If the decryption or verification fail, null is returned; otherwise, a buffer of plain-text is returned.

decrypt -- (as of 17.04)

Shorthand for cr:>decrypt cr:decrypt> .

decrypt+ sb cr -- cr

Given a crypt returned by cr:>decrypt , add the contents of the string or buffer and return the same crypt for further processing, or null if there was an error.


See also: cr:decrypt> cr:>decrypt
decrypt> cr -- b | cr -- tag b

Given a crypt returned by cr:decrypt or cr:decrypt+ , finalize the decryption and return a buffer with the decrypted data or null if there was an error.

In GCM mode or chacha1305 cipher, returns the tag as well.

If callbacks were used, then the buffer returned on TOS will be an empty one (since the results will have been written using the callback).


See also: cr:decrypt+ cr:>decrypt
ebox-sig b -- b' (as of 17.04)

Creates an encryption box signature buffer from a three-byte buffer.

ecc-curves -- a (as of 22.04)

Returns an array of maps containing "id" and "name" of all supported ECC curves.

ecc-genkey n -- priv pub (as of 16.01)

Returns a binary encoded ECC key-pair corresponding to n , or null if there was an error.

NOTE: valid values of n are the id values returned from cr:ecc-curves . Values outside of them are not accepted.


See also: cr:ecc-secret cr:ecc-sign cr:ecc-verify
ecc-secret priv pub -- b (as of 16.01)

Generates an ECC shared secret using one party's private ECC key, and the other party's public ECC key. The result is a buffer with the shared secret, or null if there was a problem.


See also: cr:ecc-genkey cr:ecc-sign cr:ecc-verify
ecc-sign priv hash -- sig (as of 16.01)

Signs the hash using ECDSA algorithms with the private key and returns an signature buffer in sig . Returns null on error.


See also: cr:ecc-genkey cr:ecc-secret cr:ecc-verify
ecc-verify pub hash sig -- T (as of 16.01)

Verifies the hash signature versus the public key of the sender, using ECDSA algorithms and returns true on successful verification or false otherwise.


See also: cr:ecc-genkey cr:ecc-secret cr:ecc-sign
ed25519 -- priv pub

Generates an "ed25519" key-pair in two buffers, corresponding to the new private-key and public-key.


See also: cr:ed25519-secret cr:ed25519-sign cr:ed25519-verify
ed25519-secret priv pub -- b

Generates an ed25519 shared secret using one party's private key priv , and the other party's public key pub . The result is a buffer which is the shared secret, or null if there was an error.


See also: cr:ed25519 cr:ed25519-sign cr:ed25519-verify
ed25519-sign priv hash -- sig

Given a buffer containing an ed25519 Diffie-Hellman private key of the sender, and another buffer containing a hash (could be a full message, but typically it's just a hash) of a message, signs the hash using DH algorithms and returns an signature buffer in sig or null if there was an error.


See also: cr:ed25519 cr:ed25519-secret cr:ed25519-verify
ed25519-verify pub hash sig -- T

Given a buffer containing an ed25519 Diffie-Hellman public key (of the sender), another buffer containing a hash which was presumably signed by the sender, and another buffer containing the DH signature, verifies the hash signature using DH algorithms and returns true on successful verification or false otherwise.


See also: cr:ed25519-genkey cr:ed25519-secret cr:ed25519-sign
edbox-sig -- b (as of 17.04)

Returns a buffer containing the correct 8-byte signature for a Chacha20Poly1305Ed25519 box.

edbox> b sb b2 -- T (as of 17.04)

Given an Ed25519 public key b , a string or buffer sb , and a "box" b2 which was created using cr:>edbox , verify that the signature is correct; returning true if it is.


See also: cr:>edbox cr:ed25519
encrypt -- (as of 17.04)

Shorthand for cr:>encrypt cr:encrypt> .

encrypt+ sb cr -- cr

Given the crypt cr returned by cr:encrypt , add the contents of the string or buffer and return the same crypt for further processing, or null if there was an error.


See also: cr:>encrypt cr:encrypt>
encrypt> cr -- b | cr -- tag b

Given the crypt returned by cr:>encrypt or cr:encrypt+ , finalize the encryption and return a buffer b with the encrypted results or null if there was an error.

In GCM mode or if using "chacha1305", a buffer tag will also be returned, which is used to verify the decryption succeeded.


See also: cr:>encrypt cr:encrypt+
ensurekey sb n -- b (as of 17.04)

Ensures that a buffer of n bytes is created from the string (or non n-sized buffer). If it needs to create b , it will use the salt value "salty8thtears" and 10000 as parameters to cr:genkey . Otherwise, if sb is already a properly sized buffer, it will just past it on.


See also: cr:genkey
genkey pwd salt iter -- key

Takes the password string or buffer pwd , the string salt , the number of iterations iter and returns a PBKDF2 compliant key in a 32 byte buffer key , or null if there was an error.


See also: cr:randkey cr:rsagenkey
hash sb -- cr

Returns the hash of a string or buffer as a crypt, or null if there was an error. The specific hash algorithm to use is determined by cr:hash! , with "blake3" being the default hash. The hash being used is task-specific, so separate tasks may use different hash functions simultaneously without concern. See also: cr:hmac .


See also: cr:hash! cr:hash+ cr:hash>s cr:hash>b cr:hmac
hash! s -- (as of 16.01)

Set the hash to use in this task. The string may be any of the values returned by cr:hashes . The default value is "blake3".

Throws an exception if given an unknown hash name.


See also: cr:hash cr:cipher!
hash+ sb cr -- cr

Take the string or buffer and add its data to the current hash in the crypt (returned from cr:hash or cr:hmac ). Returns the crypt it was given, or null if there was an error.


See also: cr:hash! cr:hash cr:hash>s cr:hash>b cr:hmac
hash>b cr -- b

Finalize the hash calculation of crypt cr , and return the hash value as a binary buffer, or null if there was an error.


See also: cr:hash! cr:hash cr:hash+ cr:hash>s cr:hmac
hash>s cr -- s

Finalize the hash calculation of crypt cr , returning the hash value as a readable string, or null if there was an error.


See also: cr:hash! cr:hash cr:hash+ cr:hash>b cr:hmac
hash@ -- s (as of 16.04)

Returns the current hash algorithm name, suitable for passing to cr:hash! .


See also: cr:hash!
hashes -- a (as of 22.04)

Returns an array of the names of all supported hashes.

hmac sb key -- cr

Take the string or buffer and return a crypt cr which is its HMAC-hash using the key key (which may be a string or a buffer), or null if there was an error. The rest of its semantics are exactly the same as cr:hash .


See also: cr:hash! cr:hash cr:hash+ cr:hash>s cr:hash>b
hotp key time #digits -- totp
needs crypto/totp

Same as cr:totp, but uses an incrementing counter rather than the time.

iv? -- T (as of 17.04)

Returns true if the current crypto settings require an "IV" (initialization vector).

pem-read s -- m | b -- m (as of 22.04)

Reads a PEM-encoded item. If given a string, reads from that named file. If given a buffer, the PEM data are in-memory. Returns a map with "name", "header", and "data"; or null if the read failed.

pem-write name header b filename -- T (as of 22.04)

Takes strings 'name' and 'header' and 'filename', and a buffer; writes them in PEM format to the file. Returns true if successful, otherwise false .

pwd-valid? s m -- T (as of 22.03)
needs crypto/password

Determines whether or not the given password meets the minimum requirements given in the map, which has numbers corresponding to cr:pwd/

pwd/ s -- m (as of 22.03)
needs crypto/password

Splits the given password string into components for analysis as to its fitness. The returned map has "uc", "lc", and "len", which are counts of number of uppercase, lowercase, and total string length. It will also have the count of characters by script, e.g. "number", "symbol", "latin", "cyrillic" etc (as per s:script? ).

pwd>hash s n -- salt hash (as of 22.03)
needs crypto/password

Given a password string and a number indicating how many random bytes of salt to create, returns a random salt string as well as the salted hash of the password

rand -- n

Generate a 64-bit cryptographically-secure pseudo-random number using the "ChaCha20" generator. Much slower than the other PRNGs, but suitable for crypto work. Each task has its own PRNG.


See also: G:rand-pcg G:rand-jsf G:rand-jit
randbuf n -- b

Generate a buffer of size n filled with pseudo-random bytes from the cryptographically strong random source.


See also: G:randbuf-pcg
randkey -- b

Returns a buffer containing a pseudo-random key for encryption, using a cryptographically strong random number generator, suitable for the currently chosen cipher.


See also: G:randbuf cr:rsagenkey cr:genkey
restore X -- (as of 17.04)

Restores the crypto settings to what they were when cr:save was invoked.


See also: cr:save
root-certs -- cert
needs crypto/root-certs

A var which contains "root certificates" which you can give as the "rootcert" key of a net transaction

rsa_decrypt b sb -- b'

Decrypt the string or buffer sb using the RSA private-key b , putting the results in b , or null on error.


See also: cr:rsa_encrypt cr:rsagenkey
rsa_encrypt b sb -- b'

Encrypt the string or buffer sb with the RSA public key b , returning the encrypted data b . The RSA corresponding private key is required to decrypt.


See also: cr:rsa_decrypt cr:rsagenkey
rsa_sign hash key -- b

Sign the hash of a message with the RSA private key , returning the signed buffer or null on error.


See also: cr:rsa_verify
rsa_verify hash key sig -- T

Verify the hash of a message with the RSA public key , against the RSA signature sig given by cr:rsa_sign . Returns true if the hash was verified, false otherwise.


See also: cr:rsa_sign
rsabox-sig -- b (as of 17.04)

Returns a buffer containing the correct 8-byte signature for a AES-256-GCM-RSA box.

rsabox> b sb b2 -- T (as of 17.04)

Verifies that the signature box b2 created using cr:>rsabox is correct given the RSA public key b and a string or buffer sb , returning true if it is.


See also: cr:>rsabox cr:rsa_genkey
rsagenkey n -- priv pub

Generate an RSA key-pair of size n . Valid values of n are 1024, 2048 and 4096. Returns the DER encoded key-pair as two buffers priv and pub , or null if there was an error.


See also: G:randbuf cr:randkey cr:rsa_encrypt cr:rsa_decrypt cr:genkey
save -- X (as of 17.04)

Returns an item encoding the current crypto settings. Use cr:restore to restore those settings.


See also: cr:restore
sbox-sig b -- b' (as of 17.04)

Creates an "signature box signature" buffer from a three-byte buffer.

sha1-hmac msg key -- hash
needs crypto/totp

Returns the SHA1-HMAC hash of the buffer or string msg given the buffer key.

shard sb n m -- a (as of 17.04)

Uses Shamir Secret Sharing to split a string or buffer into n shards, of which any m may be used to recreate the original secret. Using fewer than m shards is guaranteed to provide insufficient information to recover any of the secret. Returns an array of buffers, each of which is a shard of the original secret. Returns null if there was an error. Use cr:unshard to recover the original s .


See also: cr:unshard
tag? -- T (as of 17.04)

Returns true if the current crypto settings return a "tag" value under the encrypted data, or require a tag value for decryption. Currently, this is the same as cr:aad? , but may change as new cipher suites and modes are added.

totp key time #digits -- totp
needs crypto/totp

Given a key *buffer, a number time, and a number #digits to return, returns a "Time-based One-Time Password".

totp-epoch -- var
needs crypto/totp

A var containing the epoch to use for the TOTP. Defaults to 0.

totp-time-step -- var
needs crypto/totp

A var containing the time-step to use for TOTP. Defaults to 30 seconds.

unshard a -- b (as of 17.04)

Recombines an array containing buffers of shards produced by cr:shard to form the original (as a buffer). Returns null if there was an error.

Note: un-sharding might not fail to produce a result, even if the number of shards given was incorrect, or if the shards were incorrect; the result will simply be incorrect (and have nothing to do with the secret which was processed by cr:shard ).


See also: cr:shard
uuid -- s

Returns a cryptographically strong random UUID (RFC 4122 compliant).

uuid> s -- b

Returns a buffer 16 bytes long representing the given UUID, or null if the string is not in the correct format.

validate-pgp-sig fname -- ok (as of 18.06)
needs crypto/pgp

Takes a string fname which is a file whose PGP signature(s) are to be validated, and runs gpg --verify synchronously. It returns a number ok which is 0 if the signature is valid; otherwise, the gpg return code (-1 if gpg couldn't be launched). Requires 'gpg' be installed and in your PATH.


See also: G:-----BEGIN
validate-pwd pwd salt hash -- T (as of 22.03)
needs crypto/password

Validates the hash matches the password and salt as returned by cr:pwd>hash .

Date

Namespace: d
Description: Date and time object

word sed/description
(.time) n -- s
needs date/utils

Factor of d:time which prints the time to a string

+ d n -- d'

Add n whole days to the date d . It may be a negative number, in which case the days are subtracted from d .


See also: d:- d:=
+day d1 hr -- d2
needs date/utils

Returns a date a certain mumber of days from the given date.

+hour d1 hr -- d2
needs date/utils

Returns a date a certain mumber of hours from the given date.

+min d1 min -- d2
needs date/utils

Returns a date a certain mumber of minutes from the given date.

+msec d n -- d'

Advances the date by n milliseconds. n may be negative, in which case the date is decreased.


See also: d:new d:msec
- d1 d2 -- n

Returns the difference n , in days (and fractions of a day), between the dates.


See also: d:+ d:=
.time n --
needs date/utils

Print the number as HH:MM

/ d -- a

Split the date into an array containing, in order: year, month, day, hour, minute, second, tzHH, tzMM (time-zone offset in hours and minutes from GMT), msec, and "approx" (if not zero, how uncertain the date is in days).


See also: d:join
= d1 d2 -- T

Returns true if the dates are equal. If the dates are "approximate", then they will be considered equal if their approximate regions overlap.


See also: d:- d:+ d:?=
>fixed d -- n

Returns the "fixed" time value corresponding to the date d .


See also: d:fixed>
>hmds x -- s (as of 23.08)
needs date/format

Convert a millisecond value to a string like "1h 23m 5.678s". If x is a date, converts to msec first. Leaves off leading 0 values, e.g. if less than an hour, or minute.


See also: d:>hmds:
>hmds: x -- s (as of 23.08)
needs date/format

Convert a millisecond value to a string like "1:23:05.678". If x is a date, converts to msec first. Leaves off leading 0 values, e.g. if less than an hour, or minute.


See also: d:>hmds
>msec d -- n

Returns the number of milliseconds since Jan 01 1970 corresponding to the date. It takes the TZ of the date into account, normalizing to UTC.


See also: d:msec>
>unix d -- n

Returns the Unix time-stamp n corresponding to the date d .


See also: d:unix>
>ymd d1 -- y m d
needs date/utils

Returns the year, month and day for a given date.

?= d1 d2 n -- T (as of 20.07)
needs date/approx

Return true if the dates d1 and d2 are approximately equal, based on a maximum day-difference of n. Takes into account if the date is approximate as well.

Fri -- 5
needs date/utils

Returns the number corresponding to Friday.

Mon -- 1
needs date/utils

Returns the number corresponding to Monday.

Sat -- 6
needs date/utils

Returns the number corresponding to Saturday.

Sun -- 0
needs date/utils

Returns the number corresponding to Sunday.

Thu -- 4
needs date/utils

Returns the number corresponding to Thursday.

Tue -- 2
needs date/utils

Returns the number corresponding to Tuesday.

Wed -- 3
needs date/utils

Returns the number corresponding to Wednesday.

adjust-dst d n -- d
needs date/dst

Adjusts the date d according to the number 0-6 of the dst-zone, n. See d:dst for the meaning of that number.

alarm d m -- | d --
needs date/alarm

Set (if a map on TOS) or remove (if a date on TOS) an "alarm". The alarm will go off at or very close to the time requested (within a second). The map has the key word which is a word, or task which is a task to signal. A word will be invoked in the context of the alarm task, and must do its job quickly to avoid missing other alarms. Its SED is m -- , which is the map passed initially (so other data can be held inside) A task will have that map pushed to its queue, and then be signalled. In the even

approx! d n -- d (as of 20.07)

Sets the uncertainty, in days, of the given date, modifying it.

approx? d -- d n (as of 20.07)

Returns the uncertainty, in days, of the given date.

approximates! a -- (as of 20.07)
needs date/approx

Set the regex to use for approximate date matches. Pass an array of strings each of which is indicates "approximate". Be careful to not use text which matches your localized month names.

between d1 d2 d3 -- T (as of 22.07)

Like n:between , but for dates. true if d2 ≤ d1 ≤ d3 .

cmp d1 d2 -- n (as of 22.07)

Compare the two dates, similar to n:cmp . If d1 is chronologically before d2 , returns -1; 0 if the same, 1 if after. If either date is "approximate", then the comparison takes that into account and will consider them equal if their approximate regions overlap.

d. d --
needs date/utils

Format and print the given date in "YYYY-MM-DD" format.

default-now T -- (as of 22.05)

If true (the default), makes d:parse and d:join assume "now" as current values for all missing fields; if false , 0 is assumed.


See also: d:parse d:join
doy d -- day-in-year
needs date/utils

For a given date, return the day in the year (counting Jan 1 as '1').

dst-ofs x d -- n (as of 23.04)
needs date/daylight

Given a time-zone name and a date, returns the correct GMT offset in minutes for that date and tz

dst? d n -- d f
needs date/dst

Determines if the date d is in DST (Daylight Savings Time) or not, in accordance with the number n of the dst-zone. The values are 0=OFF, 1=ON, 2=USA, 3=EU, 4=Israel, 5=Mexico, 6=Australia.

dstinfo zone -- arr (as of 23.04)
needs date/daylight

Queries the 'libs/date/dst.db' database for the DST information for the given string zone (e.g. "America/New_York") or its numeric code (e.g. zones.id) Returns an array consisting of arrays with the "code", "name", "abbrev", "time_start" (in unix timestamp), "gmt_offset", and "dst" indicator.

dstquery zone start end -- arr (as of 18.06)
needs date/daylight

Queries the 'libs/date/dst.db' database for the DST information for the given string zone (e.g. "America/New_York") between the dates start and end. Returns an array consisting of arrays with the "code", "name", "abbrev", "time_start" (in unix timestamp), "gmt_offset", and "dst" indicator.

dstzones? -- arr
needs date/daylight

Returns an array of known country-time-zones for DST queries.

elapsed-timer n -- elapsed
needs utils/elapsed

Returns the number of ticks since timer n was started.

elapsed-timer-hmds n T -- s (as of 23.08)
needs utils/elapsed

Returns a string like "10h 23m 15.234s" if T is true , otherwise "10:23:15.234".

elapsed-timer-msec n -- msecs (as of 23.08)
needs utils/elapsed

Returns the number of milliseconds since timer n was started.

elapsed-timer-seconds n -- secs
needs utils/elapsed

Returns the number of seconds since timer n was started.

first-dow d1 dow -- d2
needs date/utils

Returns a date for the first day-of-week in the month of the given date.

fixed> n -- d

Returns a new date corresponding to the number which is a "fixed" time value. The range of valid n is 0..3652059, corresponding to 1-1-1 to 9999-12-31.


See also: d:>fixed
fixed>dow n -- n
needs date/utils

Returns the day-of-week (Sunday is 0) for a given date.

format s d -- s' | d s -- s'

Format a date according to the format string s . If a "%" character appears, the following character is a format-specifier; otherwise, it is output directly.

Valid format specifiers are:

fmt description
d day
D two-digit day
H 2-digit hour
h hour
m month
M two-digit month
N long month name
n short month name
P 2-digit hour, am/pm
p hour, am/pm
S 2-digit second
s second
T 2-digit minute
t minute
W long day name
w short day name
x 3 digit milliseconds
Y four digit year
y two digit year
z time-zone offset (HHMM)
Z time-zone offset (HH:MM)
join a -- d

Inverse of d:/ : takes an array of numbers with year, month, day, hour, minute, second, tzHH, tzMM, msec, and approx, and returns a date.

If the array is shorter than 10 items, the missing items will be given default values from the current date and time.


See also: d:/ d:parse
last-dow d1 dow -- d2
needs date/utils

Returns a date for the last day-of-week in the month of the given date.

last-month d1 -- d2
needs date/utils

Returns a date one month before the given date.

last-week d1 -- d2
needs date/utils

Returns a date one week before the given date.

last-year d1 -- d2
needs date/utils

Returns a date one year before the given date.

leap? d -- d T (as of 24.03)

Returns true if the date is in a leap-year.

mdays d -- d n (as of 24.03)

Returns the number of days in the date's month.

msec -- n

Returns the current time as number of milliseconds since Jan 01, 1970.


See also: d:ticks d:new
msec> n -- d

Returns a new date corresponding to the number of milliseconds since Jan 01 1970. It takes the current notion of timezone into account (that can be set using d:updatetz ).


See also: d:>msec
new -- d

Create a new date d , initialized with the current time.


See also: d:ticks d:msec
next-dow d1 dow -- d2
needs date/utils

Returns a date for the corresponding day-of-week on or after the given date.

next-month d1 -- d2
needs date/utils

Returns a date one month after the given date.

next-week d1 -- d2
needs date/utils

Returns a date one week after the given date.

next-year d1 -- d2
needs date/utils

Returns a date one year after the given date.

parse s -- d

Attempt to parse a valid date and/or time from a string, and return the date appropriately set if successful, or null otherwise.

The string should be in one of the ISO-8601 formats or the RFC5322 format.

It may also be "UNK" or "UNKNOWN", which returns a date which is "unknown"; "NOW", "TODAY", or "CURRENT", which return the current date; or something like "Nov 1896", in which case it will return an approximate date with the month of November, the year of 1896, and whatever the current day of the month is.

The year must be less than 100 or greater than 1000; to create a date with a year of 150 (for example), use d:join .


See also: d:join
parse-approx s -- d|null (as of 20.07)
needs date/approx

Same as d:parse, but understands meaning of various "approximate" indicators like "ABT" or "CA". The list of words which is understood can be set using d::approximates!

parse-range s -- a|null (as of 20.07)
needs date/range

Parse a "date range", e.g. "BET 2001 AND 2005"

prev-dow d1 dow -- d2
needs date/utils

Returns a date for the corresponding day-of-week on or before the given date.

rfc5322 d -- s (as of 23.04)
needs date/rfc

Format a date as per RFC-5322

start-timer n --
needs utils/elapsed

Starts a "high-resolution timer" accessed by the number n. Use d:elapsed-timer or d:elapsed-timer-seconds to read

ticks -- n (as of 18.05)

Returns a number of "ticks", which is a "high-resolution" timing counter. The specific resolution can be retrieved using d:ticks/sec .


See also: d:ticks/sec d:msec
ticks/sec -- n (as of 18.05)

Returns the resolution in "ticks per second" of the "high-resolution" timer.


See also: d:ticks d:msec
timer m -- X (as of 18.06)

Establishes a timer running on a separate task, in accordance with the options in the map. Keys are:

timer-ctrl X m -- (as of 20.03)

Controls a timer returned from d:timer . The map keys may be "repeat", the number of seconds to repeat; or "stop" which stops the timer if true .


See also: d:timer
tzadjust d n -- d' (as of 18.05)

Applies a "time zone adjustment" of n minutes offset from GMT to the date, returning a new date with the given time-zone offset. Ex: convert current time to GMT: d:new 0 d:tzadjust

Or perhaps: "2019-06-23T12:00:00+02:00" d:parse 0 d:tzadjust . resulting in 2019-06-23T10:00:00+00:00 .

unix> n -- d

Returns a new date corresponding to the Unix time-stamp n .


See also: d:>unix
unknown -- d (as of 20.07)

Returns the singleton "unknown" date.

unknown? d -- d T (as of 20.07)

Returns true if the date is "unknown".

updatetz n -- (as of 18.06)

Sets the current time-zone offset in minutes from GMT. If n is null , refreshes the notion of the system's time-zone programmatically.

year@ d -- d y
needs date/utils

Returns the year from the given date d.

ymd d -- d s
needs date/utils

Format a given date as YYYY-MM-DD, returning a string.

ymd> y m d -- d1
needs date/utils

Returns a date (at midnight) for a given year, month and day.

DB

Namespace: db
Description: SQLite database

word sed/description
SQL! param ! -- (as of 23.02)
IMMEDIATE
needs db/sql

Invokes the SQL query without returning values.

SQL[ param ] -- a (as of 23.02)
IMMEDIATE
needs db/sql

Returns an array (possibly empty) of the results of the SQL query. The rows are returned as an array of the column values.

SQL{ param } -- a (as of 23.02)
IMMEDIATE
needs db/sql

Returns an array (possibly empty) of the results of the SQL query. The rows are returned as a map of named column, value pairs.

add-func db m -- db T (as of 19.01)

Adds a new SQLite function implemented in 8th to the open database. The map may contain the following keys:

key type description default
func w an word, required if the function is a "scalar"
inverse, value w words, required if the function is an "window"
name s required: the name of the function to be added
nparams n the number of parameters the function will take; -1
step, final w words, required if the function is an "aggregate"
window T if true, declaring a "window function" false

Consult the SQLite documentation for definitions and semantics of "window", "aggregate", and "scalar".

Returns true if the addition was successful. The "func" word receives an array of parameters from the SQL call. It is its responsibility to ensure the parameters are the correct type for whatever it's going to do. Whatever it leaves on TOS is the function result, but only number, string, buffer, and null are valid SQLite types. Anything else should be converted to a string first. More details in the manual.

aes! T -- (as of 20.04)

If true , sets the SQLite cipher used for encrypted databases to AES+256+GCM. The default is Chacha20Poly1305, which is set if T is false .

again? db -- db T (as of 23.05)

(SQLite only) Returns true if the last action on the database returned a "busy" or "locked" status.

begin db -- db (as of 20.04)

Equivalent of issuing the SQL "BEGIN TRANSACTION" for the database.

bind sql x n -- sql | sql a -- sql | sql m -- sql

Bind parameters to the prepared SQL query in preparation for db:exec or db:exec-cb . The alternatives are:

  • x is an item to bind to parameter number n
  • a is an array of items to bind, in order the appear in the SQL statement
  • m is a map whose keys correspond to named parameters
bind-exec db s x w -- db (as of 19.06)

Combines bind and exec for a named sql. The s parameter is the name of a sql created previously with db:prep-name . x is an array or map of the parameters to bind to the sql. w is either null , or a word to invoke with each SQL result row as for db:exec-cb .

bind-exec[] db s a -- db a' (as of 19.07)

Like db:bind-exec , but returns an array of results from the SELECT statement. The results contain one array for each row of the result, as db:col[] is invoked on each row. An empty array is returned if no results were available, null is returned if there was an error.


See also: db:bind-exec
bind-exec{} db s a -- db a' (as of 23.04)

Same as db:bind-exec[] , but returns one map for each row as db:col{} is invoked for each.


See also: db:bind-exec
close db --

Close the database. It may not be read from or written to after this.


See also: db:open
col sql n -- sql x

Used only inside a db:exec-cb callback! Returns the value of the query column n from the sql.


See also: db:exec-cb
col[] sql -- sql a

May be used only inside a db:exec-cb callback; retrieves all the columns of the query sql into an array, in the order they appear in the query.


See also: db:exec-cb db:col{}
col{} sql -- sql m

May be used only inside a db:exec-cb callback; retrieves all the columns of the query into a map, where the keys are the column names.


See also: db:exec-cb db:col[]
commit db -- db T (as of 20.04)

Commits the transaction opened with db:begin , and returns true if the commit succeeded.

db -- db (as of 23.02)
needs db/sql

Returns the current database.

dbpush s -- n (as of 23.02)
needs db/sql

Opens the database file based on the string or map it's given. The opened database is pushed onto the list of open databases, and that database is accessible by number with db:use . The first database pushed is the default one, until db:use is invoked.

disuse n -- (as of 23.02)
needs db/sql

Closes the database #n and makes it unavailable.

each db s key fwd w -- db (as of 20.04)

Iterates over the keys in a KV database. The starting point is the key key (if null , starts from the beginning). s is the name of the database, as in the get/set words. fwd is true if the iteration order should be "forward", otherwise it's "backward". The word w is invoked with the SED: k v -- , and it can stop iteration by invoking break .

Note: the callback w must not change the database in any way!

err-handler w -- (as of 23.02)
needs db/sql

Sets the error handler for the SQL words. If a SQL error occurs, it will be invoked with a SED of s -- . The default handler throws the string it's passed.

exec db sql -- db | db s -- db

Execute the prepared statement sql , or the SQL string s on the database, running until finished.


See also: db:open db:prepare db:exec-cb
exec-cb db w sql -- db | db w s -- db

Like db:exec , but invokes the word w as a callback for each row retrieved. The SED for w is sql -- . Use db:col within the callback to retrieve the column data. Note: you must adhere to the callback SED!


See also: db:open db:prepare db:exec db:col
exec-name db w s -- db (as of 19.06)

Same as db:exec-cb , but uses the sql stored under the name s in the db . If w is null , acts the same as db:exec , using the index or named sql. Note: you must adhere to the callback SED as per db:exec-cb !


See also: db:exec-cb db:prep-name db:bind-exec
exec[] db s -- db a (as of 23.04)

Like db:bind-exec[] , but takes a SQL SELECT string (or prepared statement) without parameters.


See also: db:exec{}
exec{} db s -- db a (as of 23.04)

Like db:bind-exec{} , but takes a SQL SELECT string (or prepared statement) without parameters.


See also: db:exec[]
get db key -- db x (as of 20.04)

Get the value associated with the give key in the "kv" database. The key may be anything, but a string is preferred. It must have the same value as what was used with db:set . The value is converted back from mpack format into whatever it originally was.

get-sub db s key -- db x (as of 20.04)

Same as db:get , but gets from the named sub-database.

key db b -- db

Tells the SQLite engine it should use that key as the encryption key for the database. The database must have been created encrypted in order for this to work, and the key must exactly match the one used originally. The buffer given must be 32-bytes long, most likely created with cr:genkey from a password string entered by the user. Alternatively, you may pass the key in the 'key' key of the map given to db:open .

The key used can be changed using db:rekey .


See also: db:rekey
kind? db -- db s (as of 19.05)

Returns one of "SQLITE", "MYSQL", "ODBC", "SQLITE ENC", or "KV" for the open db.

last-rowid db -- db n (as of 19.05)

Gets the last row-id inserted (specific to SQLite databases).

mysql? -- T

Returns true if MySQL support is currently available. If true , you may use the db words to access MySQL databases. This support is provided by a third-party library which must be installed separately from 8th, from here: https://dev.mysql.com/downloads/connector/c/ .

MySQL support is only available for Pro+, so this word will always report false on less capable SKUs.


See also: db:odbc?
odbc? -- T

Returns true if ODBC support is currently available, false otherwise. If true , you may use the db words to access an ODBC database.

On Linux/RPI you need to have installed unixodbc or iodbc. On macOS you need to have configured an ODBC source. On mobile devices there is no ODBC support at present.

ODBC support is only available on Pro+, so this word will always report false on less capable SKUs.


See also: db:mysql?
open s -- db | b -- db | m -- db | null -- db

Open the SQLite (Pro+: MySQL/ODBC/KV) database indicated by the string, buffer, or map. If passed a:

type description
string the name of a file to open (or create, if it doesn't exist) as a SQLite database
buffer assumed to be an entire SQLite database as a buffer. In that case, it is treated as a read-only database
null creates an in-memory SQLite database

If a map is passed, uses these keys to create a SQLite database (possibly encrypted):

key description
create Create regardless of existence
file Required: name of db file to create
key Optional: the encryption key (as a buffer)
kind "enc" (encrypted SQLite) or "sqlite" (plain SQLite)
ro if true, the database is read-only
limits For "enc" or "sqlite", set limits according the map below

Limits are some of:

key value default max
length SQLITE_MAX_LENGTH 1G 1G
sql_length SQLITE_MAX_SQL_LENGTH 10M 1G
column SQLITE_MAX_COLUMN 64 2000
expr_depth SQLITE_MAX_EXPR_DEPTH 256 1000
compound_select SQLITE_MAX_COMPOUND_SELECT 16 500
vdbe_op SQLITE_MAX_VDBE_OP 250M 250M
func_arg SQLITE_MAX_FUNCTION_ARG 127 127
attached SQLITE_MAX_ATTACHED 10 10
pattern_length SQLITE_MAX_LIKE_PATTERN_LENGTH 50K 50K
variable_number SQLITE_MAX_VARIABLE_NUMBER 32766 32766
trigger_depth SQLITE_MAX_TRIGGER_DEPTH 1000 1000
worker_threads SQLITE_MAX_WORKER_THREADS 8 1000

Pro+: creates a MySQL, ODBC, or KV database using the map keys below:

key value DB default
charset the character set to use MySQL utf8mb4
create if true, create the file or dir if it doesn't exist KV false
db database to access MySQL
dir if false, the 'file' option is a file name not a directory KV true
dsn The normal DSN value for the ODBC connection ODBC
fetch-local if false, don't fetch all the result locally MySQL true
file the file or directory where the KV database is KV
host IP address or DNS name of server MySQL 127.0.0.1
kind "mysql", "odbc", or "kv" all
lock if false, don't do any locking KV true
map if true, write using mmap KV false
mapsize if not -1, set the max db size (10485760 default) KV -1
max-buf maximum size of buffer (BLOB) to retrieve MySQL 10000000
max-str maximum size of string to retrieve MySQL 100000
maxdbs if not 0, allow that many sub databases KV 0
meminit if false, don't ensure memory is zeroed KV true
mode the permissions for the created database KV 0664
msync if false, don't fsync metapage after commit KV true
port port on server to access MySQL 3305
pwd password for user to access server MySQL
rdahead if false, don't do readahead KV true
ro if true, the database is read-only KV false
sock string with a UNIX socket or pipe MySQL 0
sync if false, don't flush to disk for each transaction KV true
user user name to access server MySQL

Returns null if it was unable to open the database for some reason; otherwise returns a valid db.


See also: db:close
open? filename -- db flag
needs db/open

Open a presumed SQLite file. Returns 0 if the file is invalid, 1 if it is empty, and 2 if it has been initialized

prep-name db sql s -- db (as of 19.06)

Same effect as db:prepare , but stores the query under the given name s in the db item. The stored sql will be null if there was an error creating it.


See also: db:prepare db:exec-name db:sql@ db:bind-exec
prepare db s -- db sql

Prepare a SQL query from the string s , for execution against that database. Returns a sql, or null if there was an error.


See also: db:open db:exec db:exec-cb db:bind
query db qry -- result
needs db/query

Execute a query on the database db, and return the first row, as an array of items.

query-all db qry -- result
needs db/query

Execute a query on the database db, and return all rows, as an array of arrays of items.

rekey db b -- db

Tell the SQLite engine it should use the new key as the encryption key for the database. If the database was not encrypted, it will be from now on; otherwise, it will be re-encrypted with the new key.

Note: a system failure (power outage etc) during the rekeying will likely corrupt the database and render it unusable. So operate on a copy of the database when rekeying!


See also: db:key
rollback db -- db (as of 20.04)

Rolls back the transaction started with db:begin .

set db key x -- db (as of 20.04)

Puts a key-value pair into the database opened as type "kv". The key may be anything, but a string is preferred; the value can be anything. It is converted to a buffer using G:mpack before storing. Use db:get to retrieve the stored value. If null is stored, it deletes the (k,v) pair from the database. Thus, null cannot be stored (though the string "null" can).

set-sub db s key x -- db (as of 20.04)

Same as db:set , but sets to the named sub-database.

sql@ db s -- db sql (as of 19.06)

Retrieve the sql indicated by the string. The return value may be null , if db:prep-name failed or if no sql exists by the given name or index.

sql[] params s -- a (as of 23.02)
needs db/sql

Same as SQL[ , but not "immediate-mode", so the SQL can be built at runtime.

sql[np] s -- a (as of 23.02)
needs db/sql

Same as sql[] but takes no parameters for the SQL

sql{np} s -- a (as of 23.02)
needs db/sql

Same as sql{} but takes no parameters for the SQL

sql{} params s -- a (as of 23.02)
needs db/sql

Same as SQL{ , but not "immediate-mode", so the SQL can be built at runtime.

use n -- (as of 23.02)
needs db/sql

Makes the database #n the current one to access. Only necessary if more than one db:push has been invoked.

zip db -- db (as of 23.04)
needs db/zip

Add compress() and expand() SQL functions to the open database

DBUS

Namespace: DBUS
Description: D-BUS Interface

word sed/description
call DBUS m -- DBUS s (as of 21.09)
Professional version

Linux/RPI only: call the D-Bus interface as specified in the map, returns a string result The map keys are:

key type description
name s DBUS bus name
path s DBUS path
iface s DBUS interface
method s DBUS method
to n timeout in msec (default: -1)
args a array of arguments

Note: the args array must have as its first element a string containing the D-Bus signature of each following argument. Follow the D-Bus documentation for details on what that means.

init n -- DBUS (as of 21.09)
Professional version

Linux/RPI only: connect to the D-Bus system. n is 0 for the login-session bus, 1 for the system bus, and 2 for the bus that started us, if any.

Debug

Namespace: dbg
Description: Debugging words

word sed/description
.state -- (as of 24.06)

Prints the current task's state (for debugging only).

bp w --

Set a breakpoint at the word w . This is a "one-shot" breakpoint, and gets reset once you do dbg:go .


See also: dbg:go dbg:stop
bt -- (as of 23.01)
needs debug/nicer

Once dbg:stop puts you into the debug mode, invoking dbg:bt will show the backtrace of how you got where you are.

except-task@ -- t (as of 18.04)

Returns the task from which the last exception was thrown, or null if there wasn't one. Resets the last-exception task to null .


See also: G:throw
go --

Continue operation after dbg:stop or a breakpoint from dbg:bp .


See also: dbg:stop dbg:bp
prompt s -- s'
DEFFERED

Same as G:prompt but in "debug" mode.


See also: G:prompt
see w -- (as of 24.06)

Display the contents of an 8th word. Useful for debugging compilation issues.

stop --

Stops and enters an interpreter waiting for commands. Use dbg:go to continue.


See also: dbg:go dbg:bp
trace T --

Turns "tracing" on or off. If on, new words will include invocations of the words set by dbg:trace-enter and dbg:trace-leave .


See also: dbg:trace-leave dbg:trace-enter
trace-enter w --
needs debug/common

If dbg:trace is on, invoke w upon entry to any compiled word. If w is null, turns off the trace. The word must consume TOS. The SED of w is w -- .


See also: dbg:trace dbg:trace-leave
trace-leave w --
needs debug/common

If dbg:trace is on, invoke w upon exit from any compiled word. If null, turns off the trace. The word must consume TOS. The SED of w is w -- .


See also: dbg:trace dbg:trace-enter

DOM

Namespace: DOM
Description: DOM (Document Object Model)

word sed/description
+ DOM1 DOM2 -- DOM1 (as of 21.08)

Adds DOM2 as a child of DOM1 , and assigns DOM1 as the parent of DOM2 .

- DOM1 DOM2 -- DOM1 (as of 21.08)

Removes DOM2 from the children of DOM1 , making DOM2 parentless.

attr! DOM s x -- DOM | DOM m -- DOM (as of 21.08)

Sets the attribute with that name in the DOM. If a map is given, it is added to the DOM attributes (per key,val).

attr@ DOM s -- DOM x (as of 21.08)

Gets the attribute with that name from the DOM. Returns null if the attribute doesn't exist.

attrs DOM -- DOM m (as of 21.09)

Returns the "attributes" of the DOM node, which may be null.

children DOM -- DOM a (as of 21.08)

Gets an array (perhaps empty) containing the child nodes of the DOM.

css-parse sb -- m (as of 21.09)

Takes a string or buffer containing CSS, and parses it into a map which can be used by DOM:css-apply . Only understands a subset of CSS3 at the moment. Returns null on error.

each DOM w n -- DOM (as of 21.08)

Iterates the DOM, passing the word w each element in turn. Iteration is stopped with G:break , and will not go farther down the DOM than 'n' nodes.

The SED of w is DOM n -- , where 'n' is the current depth.

find dom w depth -- dom a (as of 21.08)
needs dom/find

Similar to DOM:each , but the SED of w is dom n -- T , where true means keep this item, and 'n' is the depth of the item from the source DOM. The DOM nodes found are returned in an array.

new s DOM -- DOM' (as of 21.08)

Create a new DOM node, with the string "type", and DOM "parent" -- either or both may be null.

type DOM -- DOM s (as of 21.09)

Returns the "type" of the DOM node, which may be null.

File

Namespace: f
Description: File operations

word sed/description
/ s -- a (as of 21.02)

Separates the "path" s into an array [drive,path,filename,extension,separator] . Inverse of f:join .


See also: f:join f:relpath f:abspath
>posix s -- s' (as of 23.03)

Converts any Windows backslash \ characters in the string to POSIX forward / slashes.

abspath f -- s | s -- s'

Given a file or string containing a file name, returns a string containing the absolute path of the original file name.


See also: f:relpath
absrel x rel -- abs (as of 21.02)
needs file/absrel

Like f:abspath, but assumes x is relative to the path given by rel

append f -- f (as of 17.02)

Seek to the end of the file in preparation for appending to it.


See also: f:write
associate ext desc longdesc app --

"Associate" the application named app as the default for opening the file extension ext , with, a short description of desc and a long description of longdesc . The short description must not have spaces in it.

Note: only on Windows currently

atime f -- f d (as of 16.05)

Returns a time-stamp of when the file was last accessed.

autodel f -- f (as of 22.03)

Makes the file automatically delete itself when the program ends, or when the its refcount goes to 0.

canwrite? s -- T

Returns true if it is possible to write to the named file, or false otherwise. If the file does not exist, it determines whether or not the parent directory is writeable.

chmod f n -- | f s -- | s n -- | s s' --

Change the access "mode" of the file to that indicated in the string or number. If the mode is a string, it can contain "r" = "readable", "w" = "writeable", "x" = "executable". By default, it only affects "owner-modes". To affect "group" modes, use 'g'; to affect 'other' modes, use 'o'; to affect all, use 'a'.

Ex: "o+x" will add execute permissions for 'others'. In order to apply to more than one you issue two separate stanzas, e.g. "o+xg+x". If a "+" is included then the modes are added to the existing one, if "-" they are removed, otherwise they are set exactly.

The file given may be an open file or a string with the name of a file. If the mode is a number, then that OS-specific mode will be set exactly without interpretation by 8th.


See also: f:getmod
close f --

Close the file. I/O to that file will not be possible if, for example, a var stored f .


See also: f:open-ro f:create f:open
copy src dest -- T

Try to copy the file named src to a new file named dest , which will be removed if it already exists. If dest is a directory, an appropriately named file will be created there. If the copy succeeds, true will be on TOS, otherwise false .


See also: f:copydir
copydir src dest -- T

Try to recursively copy the directory named src to a new one named, dest . If the copy succeeds, true will be on TOS, otherwise false .

create s -- f

Create the file named by the string s , returning the file f .

Note: an existing file by the same name will be destroyed. If that is not your intention, use f:open instead.

ctime f -- f d

Returns the 'creation' time of the file or string naming a file, as a date.


See also: f:mtime f:atime
dir? s -- T

Returns true if the s represents a directory.

dname s -- s'

Returns the path of the filename, excluding the file name as returned by f:fname .


See also: f:fname f:abspath f:relpath
eachbuf f w n -- f | s w n --

Similar to f:eachline , but passes a buffer of up to n bytes to the word w, whose SED is b -- . Responds to break .

NOTE: the same actual buffer is passed to w each time.


See also: f:getline s:eachline f:eachline
eachline f w -- f | s w --

Similar to s:eachline , but leaves the file on TOS when done. The SED of w is s -- . Responds to break . If a string is passed rather than a file, it is assumed to be the name of a file, and the string is not left on TOS after running.

If the file cannot be read (or opened, if a string), t:err? will report an error.

NOTE: the same actual string is passed to w each time, so if you want to store the data you must clone it (or use const ).


See also: f:getline s:eachline f:eachbuf
enssep s -- s'

Ensure that the file name given by the string ends with the OS-appropriate directory-separator. Use this instead of hard-coding "\" or "/".

eof? f -- f T (as of 18.03)

Returns true if the file is at "end of file".

exec s -- (as of 23.01)

Attempts to execute the file as 8th code, unpacking and decrypting it if necessary. Throws on failure.

exists? s -- T

Returns true if the s represents a file or directory which exists.

flush f -- f

Make sure any buffers containing unwritten data in the file are written.

fname s -- s'

Returns the last part (exclusive of path) of the filename.


See also: f:dname f:abspath f:relpath
getb f -- f b
needs file/getc

Read a single byte from the given file. If no byte is available, null is returned.

getc f -- f c
needs file/getc

Read a single Unicode character from the given file. If no character is available, null is returned.

getline f -- f s

Read one line from the file f . "line" means up to but not including a newline or carriage-return character ("\n" or "\r"). Returns null if no data are available (or trying to read past end-of-file).


See also: f:eachline
getmod f -- n | s -- n

Returns the OS-specific numeric "mode" of the file. See your OS documentation for the specific interpretation of the "mode". It may be given an open file or a string representing the name of a file.


See also: f:chmod
glob s -- a

Returns an array of file names matching the string pattern s . The "glob" pattern is not a regex but rather the usual "*" and "?" file matching.


See also: f:rglob
glob-links T -- (as of 22.01)

If true , then f:rglob will descend into directories which are symbolic links. The default is to not do so.

glob-nocase T --

If T is true , then make the f:glob word case-insensitive; otherwise it is case-sensitive.

The default for this setting is true on Windows and macOS, and false on all other systems.


See also: f:glob f:rglob
gunz readcb writecb -- n (as of 22.04)

"gzip -d" equivalent. Takes a read callback word to get buffers of data to decompress, and a write callback to write the decompressed data. Returns 0 on success, or a 'miniz' error code.

The SED for readcb is -- b ; if no more data is available, returns null . The SED for writecb is b -- .

homedir -- s (as of 19.08)

Returns the home-directory for the current user

homedir! s -- (as of 21.04)

Sets the value returned by f:homedir . Useful if running as 'root' but not installed in the root directory.


See also: f:homedir
include s --

Read the named file and interpret it as 8th code. Looks for the file in this order:

  1. the file name as given, then
  2. that name in the "incs" asset, then
  3. in the app:datadir , then
  4. in the directory pointed to by the EIGHTHLIB environment variable (if any), then finally
  5. in app:8thdir .

Throws an exception if it cannot load the file.


See also: G:needs f:slurp app:asset G:requires
ioctl f req x -- f x' n | f null (as of 20.06)
Hobbyist version

(NOT Windows) Issues an ioctl system call on the given file or net (socket). The parameter req is a number indicating which ioctl call is to be performed, and x is either an integer number, a string, or a buffer, depending on the IOCTL call.

Returns a number and the value x' is of the same type as x .

Note: This is OS and ioctl-call specific. Use with caution!

If f isn't a file or a net, or if x is an invalid type, returns null. On ioctl error, sets t:err? return value.

join a -- s (as of 21.02)

Joins the array containing strings [drive,path,filename,extension,separator] into a file name. Inverse of f:/ . Returns null if any of the components is not a string or is missing.


See also: f:/ f:relpath f:abspath
launch s params --

Launches the named file. If it is executable, executes it; if it is a document, starts the appropriate application to open it; if it is a folder, displays it in the OS-specific folder viewer.

Give the parameter string params (may be null ) if needed.

On mobile devices this is the same as passing s to net:launch.

link orig link -- T

Makes a symbolic link named link , to the file named orig . Returns true on success, or false on failure.

Note: Only on macOS, Linux, and RPI.

link> s -- s'

If the named file or folder named is a link or alias, returns what it points to; otherwise returns the original name.

link? s -- T

Returns true if the named file is a link to a file.

lock f ofs len x -- f T (as of 22.03)

Locks or unlocks the file.

When locking: creates an "shared" lock (e.g. "read-only" access) if x is true , and an "exclusive" (no access) if false . ofs and len are numbers which are the offset in the file to start locking, and the number of bytes to lock. If len is 0, it means "lock the rest of the file". Therefore, 0 0 false f:lock will lock the entire file, forbidding any other process access.

Returns true if the lock was acquired, or false (and t:err? set) if not.

To unlock, pass null as x .

mkdir s -- T

Create the named directory. Returns true on success, else false .

mmap s T -- b

Opens the named file as "memory-mapped". If T is true if the file should be read-only, otherwise it should be writeable. Note that resizing the file is not possible, it must be whatever size is required before opening it. Returns a buffer containing the contents of the mapped file.


See also: f:mmap-range f:mmap-range? f:open
mmap-range s T start end -- b

Same as f:mmap , but only maps the file from start to end , which must be numbers within the range of the file size. The start value might be rounded-down to an OS page boundary.


See also: f:mmap f:mmap-range? f:open
mmap-range? b -- b start end

Returns start and end offsets of a buffer returned from f:mmap or f:mmap-range , or null if it was not created by f:mmap or the equivalent.


See also: f:mmap f:mmap-range f:open
mtime f -- f d

Returns the 'last-modified' time of the file or string naming a file, as a date.


See also: f:ctime f:atime
mv oldname newname -- T

Rename ("move") the file named oldname to the newname . Returns true on success, false otherwise.


See also: f:rm f:rmdir
name@ f -- f s (as of 21.02)

Gets the name of the file.

open s -- f | n -- f

Opens the file named by the string for read/write access. Returns null if there was an error (no access, or file doesn't exist). If a number is given instead, it is presumed to refer to an already open file-descriptor, and the file returned will wrap it.


See also: f:open-ro f:create f:close
open! s -- f (as of 22.03)

Same as f:open , but creates the file if (and only if) it doesn't already exist.

open-ro s -- f

Same as f:open , but the file is opened in "read-only" mode.


See also: f:open
popen s T -- f

Returns a new file which is a "pipe" from which the results of the command s can be read. If it was not successful, returns null . If T is true , the returned pipe is read-only; otherwise it is write-only.


See also: f:open
popen3 s -- a

Takes a string with the name and perhaps parameters of an external command to invoke and returns an array [in,out,err,pid] . The first three are files which can be used to write to the command and read its output. The last is the process-id of the command. Returns null if anything failed.

Not on mobile platforms.

print s -- (as of 16.02)
needs file/print

Attempts to print the file named by the string using the default OS-specific method. Does not notify if there is an error. Uses CUPS on macOS, Linux and RPI; uses "ShellExecute" on Windows.

Currently does nothing on mobile platforms. As of 20.01 moved to file/print library

read f sb n -- f sb n | f n -- f b n

Read n bytes from the open file, into the string or buffer sb . The number of bytes actually read is left on TOS and sb contains that many bytes. If there was a problem, null is on TOS and sb may contain partial data,

If no string or buffer is given then a buffer is created to accommodate n bytes of data.


See also: f:open f:write f:read-buf
read-buf f n -- f b (as of 22.04)

Read n bytes from the file f , creating a new buffer with the data, or null on error (setting t:err? ).

This should be used in preference to f:read because the SED is simpler, and the number of bytes read is implicit in the length of the returned buffer.


See also: f:open f:write f:read
read? f s n -- f s n (as of 19.06)

Same as f:read , but will read fewer than n bytes if that's all there is. In particular, if reading from a device rather than a disk-file it may read fewer bytes.


See also: f:read
relpath f s -- s' | name s -- s'

Returns a file name, which is the original file's name adjusted relative to the folder name s . It may be given a file or a string naming a file. If a relative path is impossible to produce, the returned path will be an absolute one.


See also: f:abspath
rglob s -- a

Same as glob , but recursively finds all files in subdirectories as well.


See also: f:glob
rm s -- T

Remove the named file from the system. Returns true if it succeeded, false otherwise.


See also: f:rmdir f:mv
rmdir s -- T

Remove the named directory from the system, as well as all its contents. Returns true if it succeeded, false otherwise.


See also: f:rm f:mv
seek f n -- f

Seek to position n in the file. If n is negative, it seeks from the end of the file, otherwise it seeks from the beginning.


See also: f:open f:create f:read f:tell
sep -- n

Returns the ASCII code of the character used for separating path components. Use this instead of hard-coding "\" or "/".

size f -- f n

Returns the byte size of a regular file or string naming a file f . If f is a zip-file, returns the number of entries in it.

slurp s -- b | f -- b

Open the file named by the string (or an open file) and return its contents as a buffer. The name may begin with "~" to represent the user's HOME directory. If the file does not exist or if there is not enough memory to hold its contents, null is returned. The buffer returned is read-only, and is memory-mapped onto the file's contents.

sparse? f -- T | s -- T (as of 19.02)

If the file (or string containing the name of a file) is a "sparse file", returns true . Otherwise, return false .

spit x s -- (as of 21.03)

Inverse of f:slurp . Creates a file named s and writes the buffer or string x to it. Check G:error? for failure.

stderr -- f

Open a file corresponding to the "standard error output". Desktop systems only: returns null on mobile systems.


See also: f:stdin f:stdout
stdin -- f

Open a file corresponding to the "standard input". Desktop systems only: returns null on mobile systems.


See also: f:stdout f:stderr
stdout -- f

Open a file corresponding to the "standard output". Desktop systems only: returns null on mobile systems.


See also: f:stdin f:stderr
tell f -- f n

Returns the current read or write position in the file.


See also: f:open f:create f:read f:seek
tempfile -- f (as of 22.03)

Creates a temporary file which will be automatically deleted as per f:autodel .

times s d1 d2 -- | s n1 n2 -- (as of 16.04)

Sets the access time d1 and modification time d2 of the named file. If either is null , do not change that time; otherwise either may be a number (Unix timestamp) or a date.

tmpspit x -- s (as of 21.03)

Uses f:spit to write the item x to a temporary file. Returns the name of the temporary file.

trash s -- T

Try to move the named file or folder named to the OS-specific "trash". On success, returns true , otherwise false .

truncate f n -- f | s n -- s (as of 19.02)

Changes the length of the file or string naming a file to be n bytes. Sets t:err? , which will indicate what failed if there was a failure.

ungetb f b -- f
needs file/getc

Take the given byte and "unget" it, so that the next f:getb will return it.

ungetc f c -- f
needs file/getc

Take the given Unicode character and "unget" it, so that the next f:getc will return it.

unzip f s T -- f (as of 16.04)

Unpacks the entire ZIP file to the named destination folder. If T is true , overwrites any existing entry by that name. Otherwise, leaves them alone.


See also: f:unzip-entry
unzip-entry f s ix T -- f (as of 16.04)

Unpacks one item from the ZIP file designated by the index into the named destination folder. If T is true , overwrites an existing entry by that name. Otherwise, leaves it alone.


See also: f:unzip
watch m -- X (as of 18.06)

Watches files or sockets listed in the key "files" of the map, for events listed in the "events" key. Returns an item which when refcounted to 0 (or when G:free is invoked on it) will release the watches on the items listed. Keys in opts may be:

write f sb -- f n

Write the string or buffer sb to the open file. The number of bytes written is left on TOS, or null if there was a problem.


See also: f:open f:read f:create f:writen
writen f sb n -- f n

Write n bytes to the file from the string or buffer sb . The number of bytes written is left on TOS, or null if there was a problem.


See also: f:write
zip+ f s x -- f

Add item x to the new zip-file f , giving it the name s in the zip directory. If x is a string, it is considered to be a file-name. If it is a buffer, it is considered to be data to be put in the zip-file.


See also: f:zipnew f:zipsave f:zipopen f:zip@
zip@ f x -- f b

Read item x from the zip file f , returning a buffer b or null . If x is a number, then the item with that index is returned. If x is a string, the first item with that name is returned.


See also: f:zipnew f:zipsave f:zip+ f:zipopen
zipentry f ix -- f d n s

Returns information about the entry at index ix in the zip file. Returns the string name of the entry s , its size n in bytes, and the date of the item.

zipnew -- f

Create a new zip-file in-memory. The file can be saved to disk using f:zipsave .


See also: f:zipsave f:zip+ f:zipopen f:zip@
zipopen sb -- f

Open the zip-file sb , which may be either a buffer of zip data, or a string denoting a file-name, creating the zip file f . Returns null if there was an error.


See also: f:zipnew f:zipsave f:zip+ f:zip@
zipsave f s --

Save the in-memory zip-file f created with f:zipnew or opened with f:zipopen to the file named by the string s . After saving the zip, no further write operations are possible on it.


See also: f:zipnew f:zip+ f:zipopen f:zip@

Font

Namespace: font
Description: Font utilities

word sed/description
atlas! font s -- n (as of 21.06)

Adds the font to the global font-atlas under the given name. Returns a number which can be used as an alternative to the name to access this specific font. The name might also be null , in which case the font can only be accessed by its number. Adding a font to the atlas with the same name as a previously added font will make the previously added font accessible solely by the number it was assigned.

atlas@ n -- font | s -- font (as of 21.06)

Retrieves a font from the font-atlas. The parameter is either a number (as returned by font:atlas! ) or a string given to font:atlas! . If the font does not exist, null is returned.

default-size n -- (as of 21.06)

Sets the default font size (if not otherwise specified) to n pixels, for fonts declared or created after it is invoked.. The default value is 12.

default-size@ -- n (as of 21.09)

Gets the default font size (in pixels)

info font -- font m (as of 17.04)

Returns a map containing information about the given font (if null , the current nk font). The keys returned include:

key description
ascent Maximum height of font above baseline
desc A textual description of the font as ".s" would display it
descent Maximum depth of font below baseline
height Pixel height the font was created at
lineGap Spacing between one row's descent and next row's ascent
over_h Horizontal oversampling (1-8)
over_v Vertical oversampling (1-8)

If any codepages have been loaded, the key "pages" is an array of maps:

key description
cp The page id (the codepage/256)
nchars Number of valid characters (codepoints) in the page
ls -- a

Returns an array of strings containing the names of all fonts known to the system.

measure font s -- font n

Returns the width in pixels of the string using that font.

new null -- font | s -- font | b -- font | n -- font | a -- font | font -- font | m -- font

Creates a new font. If it is passed a:

  • null: the default system font will be produced
  • string: following the same rules as for any gui item (see the manual)
  • buffer: containing a TTF or OTF font file (e.g. from an asset)
  • number: the default font in that pixel size
  • array: a list of any of these possible items, the first one to yield a font wins
  • font: creates a clone of the font
  • map: with the keys "size" (in pixels), "font" (any of the above), "name" by which it is known in the atlas
oversample hor ver -- (as of 21.06)

Sets the "oversampling" values (horizontal, vertical) for succeeding font declarations. These oversampling values are used when rendering the font into bitmaps for display. The values may be between 1 and 8, inclusive. Large values increase the size of the font bitmaps, but may make the image more legible. The default values are 3 and 1, meaning horizontal oversampling only, which produces reasonably sized bitmaps with nice quality.

pixels font n -- font

Changes the size of the font to n pixels.

pixels? font -- font n

Returns the font's height in pixels.

system n -- s
DEFFERED
needs font/loaded

Returns a string for a 'system font' in the given pixel size. The default fonts are searched; if none of them are found, the first font returned by font:ls is used.

system -- a
needs font/loaded

Returns an array containing all the fonts present in the system's usual font locations.

Global

Namespace: G
Description: Catch-all class

word sed/description
! x v -- | v x --

Put the item x in the variable v . x may be from any namespace, but if it itself is a variable then the first SED x v -- is required.


See also: G:@ G:var G:var,
!if -- (as of 22.06)
IMMEDIATE

Same as not if but more efficient.


See also: if else then not
#! --
IMMEDIATE

Like \ , but intended for use on Linux or macOS where this tells the system which interpreter to use. If you do use it this way, make sure to put a space after it so 8th recognizes it properly and ignores it.


See also: G:SED: G:-- G:\ G:(*
## n --

Set the precision, e.g. the number n of digits to the right of the decimal (for floating point; integers will be printed only to the left of the decimal). The default is 5. Setting it to 0 will print as many places as are necessary.


See also: G:n#
#if f --
IMMEDIATE

Analogous to if but intended for "pre-processing". It parses the input stream for "#then", and then parses that for "#else". It then evaluates the #else or #then text depending on the value held in TOS. Used mainly to select different code to compile based on platform or other load-time environmental factors.


See also: G:if
' -- w
IMMEDIATE

Returns the word whose name is <name> , and put it on TOS. Returns null if it cannot find <name> .


See also: w:find
( --
IMMEDIATE

Begin compiling a new anonymous word. The ) word finishes the process; if you forget it, you'll stay in compile mode forever…


See also: G:) G:: G:; G:;;
(* <*)> -- (as of 17.06)
IMMEDIATE

Multi-line comment. This word parses until it finds a "*)" sequence in the input, and will drop all that text. Handles nested comments of its own type, e.g. (* foo (* bar *) *) .


See also: \ --
(:) s --

Begin defining the word named s .

(code) -- used allocated

Returns the number of bytes of code space used as well as the total amount allocated . These are global over all tasks.

(defer) s -- (as of 20.04)

Same as G:defer , but instead of parsing the name to create it is given a string.


See also: w:undo w:is G:defer G:deferred:
(dump) x -- s (as of 20.04)

Creates a string containing a hex-dump of the contents of x .

(getc) -- n

Returns one character from stdin or the console. Reads as an ASCII character from stdin, or a Unicode character from the console.


See also: G:(gets) con:accept con:accept-pwd
(gets) -- s

Read a string from stdin or the console.


See also: G:(getc) con:accept con:accept-pwd
(interp) --

Start the "REPL loop". Used internally.

(log) x --

Write the item x to the 8th logging facility, converting it to a string if necessary. Only the first 511 bytes of the string will be logged.

(needs) s -- (as of 17.05)

Load the named 8th library. This is a factor of G:needs , but is useful if you need to load a library which has a space in the file or folder name (8th does not have such libraries), or if you want to load a library dynamically.

(parseln) -- s

Same as G:parseln , but does not consume the CR/LF at the end of the line if the current character is at the end of the line


See also: G:parse G:parsews G:parsech
(putc) n --

Print the Unicode character to stdout.


See also: G:putc G:. G:(puts)
(puts) s --

Print the string to stdout.


See also: G:putc G:. G:(putc)
(stat) n -- a

For the namespace identifier n , return an array containing in order:

  1. the number of items on the free list
  2. the total number of items allocated
  3. the number of words in the namespace
  4. the namespace short name
  5. the namespace long name
  6. the number of abandoned items

If an invalid namespace number is given, returns null .

Note: this only returns valid information if you've turned on allocation counting with G:counting-allocations !

(with) s --

Internal factor of G:with

) -- w
IMMEDIATE

End compilation of a new anonymous word, leaving it on TOS. If there is no matching ( , an exception will be thrown.


See also: G:( G:: G:; G:;;
+hook w -- n (as of 19.04)

Adds a "last-gasp handler". It gets the name of any item the interpreter cannot handle. It returns the index of this gasp-handler, which may be passed to G:-hook in order to remove it.

The SED for w is: s -- T . If it recognizes the item, it processes it and returns true ; otherwise it returns false .


See also: G:-hook G:.hook
+ref x -- x

Increase the "reference-count" of the item x . Usually you should not need to use this.


See also: G:-ref G:ref@
,# n --

Sets the thousands separator for printing numbers to the ASCII character given by the number n . If zero, no separator will be used (the default).


See also: G:.# G:n# G:c# s:strfmt s:fmt
-- --
IMMEDIATE

Same as \\ , this is a SQL-style comment.


See also: G:SED: G:#! G:\ G:(*
-----BEGIN <...> -- (as of 18.06)
needs crypto/pgp

Ignores everything from the "-----BEGIN " until and including "-----END PGP SIGNATURE-----". This allows you to embed PGP signatures in your scripts, allowing your users to be confident the script has not been modified and that it is from you.


See also: cr:validate-pgp-sig
-Inf -- n

Put the number with value -Inf on TOS, "negative infinity".


See also: G:Inf G:NaN
-Inf? o -- o f
needs math/isa

Return f which is true if the item o is -Inf, or false otherwise.

-hook n -- (as of 19.04)

Removes a "last-gasp handler" added with G:+hook . If the value n is not one which was returned by G:+hook , or if the handler has already been removed, it will be ignored.


See also: G:+hook G:.hook
-ref x -- x

Decrease the "reference-count" of the item x . Usually you should not need to use this.


See also: G:+ref G:ref@
-rot a b c -- c a b

Move the item in TOS to the third position on the stack.


See also: G:rot G:swap G:over G:drop G:nip G:tuck
. x --

Print the item x , converting it to a string first if necessary.


See also: G:putc G:(putc) G:(puts)
.# n --

Sets the decimal separator for printing numbers to the ASCII character given by the number n ; if zero, a period will be used (the default).


See also: G:,# G:n# G:c# s:strfmt s:fmt
.hook -- (as of 19.04)

Displays active hooks installed via G:+hook along with their index numbers.


See also: G:+hook G:-hook
.needs -- (as of 16.04)

Prints the names of all libraries loaded by G:needs , one per line.


See also: G:needs
.r --

Print the top 10 items in the "r-stack", in the same manner that G:.s does for the data stack.

.s --

Display up to st:dot-depth items on top of the data stack (default is 10 items). The display shows the index on the stack, the namespace name, the address of the item, its reference-count and finally its value. If there is nothing on the stack, prints "Stack empty". If the item is currently locked (see G:lock ), an asterisk ("*") appears after the stack index and before the namespace name. TOS is item '0'.

The first item (TOS) also shows the depth of the stack, e.g. 0/11 if there are 11 items on the stack.


See also: G:.r G:depth
.s-truncate T -- (as of 20.08)

Controls whether or not G:.s truncates output. By default it does; to disable truncation, pass false .

.stats --
needs utils/stats

Display system statistics. The first line shows how much code space has been used vs. how much is allocated (in bytes). Then, for each namespace it shows its name followed by how many words are currently defined in it, how many data items of that type are in use, how large the pool is for that namespace and finally, how many pools have been allocated.

.ver --

Print the version of 8th, including build number, OS and bit-size, and customer id. Does nothing, in mobile builds.


See also: G:8thver? G:buildver? G:build?
.with --

Displays the current "with list".


See also: G:with: G:;with
0; x --

If x evaluates false , drop it and exit the word; otherwise, continue execution. Used within a word instead of the phrase dup !if drop ;; then .

2dip a b c w -- w(a) b c
needs combinators/2dip

Implementation of Factor's "2dip" combinator. Invokes w on the items in position 3 (etc.) on the stack, moving the items in positions 1 and 2 out of the way and restoring them afterwords to TOS.

2drop a b c d -- a b

Drop the two top items from the stack.


See also: G:dup G:2dup G:2over G:2swap
2dup a b -- a b a b

Duplicate the two top items on the stack.


See also: G:dup G:2drop G:2over G:2swap
2nip a b c -- c (as of 22.05)

Drops the two items under TOS.


See also: G:tuck G:drop G:dup G:swap G:over G:nip
2over a b c d -- a b c d a b

Copy items in positions 3 and 4 to TOS.


See also: G:dup G:2dup G:2drop G:2swap
2swap a b c d -- c d a b

Like G:swap but for the two sets of two items on TOS.


See also: G:dup G:2dup G:2drop G:2over
2tuck a b c d -- c d a b c d (as of 23.06)

Same as tuck but copies the top two items on the stack under the two items below them.

3drop a b c d -- a (as of 22.05)

Drops the three top items from the stack.


See also: G:dup G:2dup G:2over G:2swap
3drop x y z --
needs stack/3drop

Drops three items off the data stack

3dup a b c -- a b c a b c (as of 22.08)

Duplicates the three top items on the stack.


See also: G:dup G:2dup G:2drop G:2over G:2swap
3rev a b c -- c b a (as of 21.03)

Same effect as -rot swap but faster and more efficient.

4drop x y z a --
needs stack/3drop

Drops four items off the data stack

8thdt? -- s (as of 18.01)

Returns a readable string containing the build date of 8th.

8thsku -- n (as of 21.03)

Returns the running 8th's SKU: 0 = Free, 1 = Hobbyist, 2 = Professional, 3 = Enterprise

8thver? -- s

Returns a string of the 8th version. e.g.: "23.08" or the like.


See also: G:buildver? G:build? G:.ver
8thvernum? -- n (as of 21.02)

Returns the 8th version as a number in the format major, minor, patch, e.g. '210100'.

: --
IMMEDIATE

Begin defining the word named <name> . May only be used in interpret mode, and may not be used inside another word definition (e.g. nested words are not allowed).


See also: G:; G:( G:) G:;;
; --
IMMEDIATE

Terminate a word definition which was started with G:: . May only be used in compile mode. Must be used after an initial : .


See also: G:: G:( G:)
;; --
IMMEDIATE

Exits the current word immediately, prior to the usual terminating ; .


See also: G:; G:;then G:break
;;; --
IMMEDIATE

Immediately exit the word which invoked the current one (as opposed to G:;; , which exits only the current word).


See also: G:;; G:; G:break
;then -- (as of 17.08)
IMMEDIATE

The equivalent of ;; then to make code a bit more compact.

;with --
IMMEDIATE

Drops the last with: namespace from the with list.


See also: G:with:
>clip x --

Take an item x and put it on the system clipboard. The item's string representation will be put on the clipboard as if G:>s was performed on it first.

>json x -- s

Take an item x and convert it to its JSON representation. An equivalent item may be retrieved by giving the resultant JSON to json> .

Note: this does not work with all namespaces. It only works with the JSON standard types of number, boolean, string, array, map, and null. If you've put e.g. a word in the array or map, it will be converted to the name of the word, which standard JSON parsers will not accept.


See also: G:json>
>kind x -- n

Returns the numeric namespace identifier of the item x . Each namespace identifying number is obtained by using its name in the ns: namespace. Ex: the identifier of strings is ns:s .


See also: G:ns
>n sb -- n | n -- n | T -- n

Convert the string or buffer to the number n , obeying the current numeric base . If a number is passed, it is simply returned. If a boolean is passed, returns 1 for true and 0 for false . If none of the above is passed, or the string cannot be converted to a number in the current base , returns null .


See also: G:>s
>r x --

Pop the item x from the data-stack and push it onto the r-stack.


See also: G:r> G:r@ G:rswap G:rdrop
>s x -- s

Convert the item x to its string representation s . If x is already a string, returns the same string.


See also: G:>n
?: x1 x2 -- x' (as of 18.08)

Returns 'x2' if x1 is null , otherwise x1 . Same effect as swap null? if drop else nip then , but much more efficient.

?@ x1 x2 -- x3 (as of 23.04)

Similar to ?: , but if x1 is null , then if x2 is a var gets the value it holds, while if x2 is a word, invokes it.

@ v -- x

Returns the contents of the variable v , which may contain an item from any namespace.


See also: G:!
BITMAP: bits , bits2 , ... ; -- (as of 20.06)
needs utils/bitmap

Create a set of words for each 'bits' value, assuming 'little-endian' order. That is, the first values will be at the least-significant end. For each 'name', creates 'name_bits', 'name_mask', 'name_shift', 'name@', and 'name!'

ENUM: startfrom ... ; -- (as of 20.01)
needs utils/enums

Same as G:enum: but stops at ";" instead of "enum;"

FLAG: startfrom ... ; -- (as of 20.01)
needs utils/enums

Like G:ENUM:, but creates a value of 1 shifted left the number of the enum.

I -- n (as of 22.04)

Inside loop , loop- , times return the current loop index.

Note: the loop index is a singleton, so if you want to store it, clone it first.


See also: G:J G:K G:X
Inf -- n

Put the number with value Inf on TOS, "positive infinity".


See also: G:-Inf G:NaN
Inf? o -- o t
needs math/isa

Return true if the item o is Inf, or false otherwise.

J -- n (as of 22.04)

Inside loop , loop- , times return the loop index of the next outer loop.

Note: the loop index is a singleton, so if you want to store it, clone it first.


See also: G:I G:K G:X
K -- n (as of 22.04)

Inside loop , loop- , times return the loop index of the second outer loop.

Note: the loop index is a singleton, so if you want to store it, clone it first.


See also: G:I G:J G:X
NaN -- n

Put the number with value NaN on TOS. This is generally the result of dividing zero by zero, for example. Any numeric operation on NaN propagates, so e.g.: NaN 0 + gives NaN .


See also: G:Inf G:-Inf
NaN? o -- o t
needs math/isa

Return true if the item o is the same as NaN, or false otherwise.

SED-CHECK f --
needs debug/sed

Enable (if f is true) or disable SED checking. The check depends on proper use of SED:

SED: --
needs debug/sed

Overwrites the built-in SED: (which is simply a comment). If true SED-CHECK has been invoked, then any word using this to declare a stack-effect-diagram will have it checked on entry and exit. The SED must use namespace identifiers (e.g. "s" or "n" etc) in order for SED: to properly check data types. If the SED doesn't match the stack at runtime, an exception will be thrown. This can also be enabled by using the '-g' CLI option to 8th.

NOTE: use of this word will slow performance, so it should not be enabled in production code.

NOTE: does not check the r-stack, and the SED declaration must be simple. e.g.: SED: n n -- n or something like that.

SED: -- (as of 18.08)

The builtin version is just a "comment to end of line". It is intended to be overwritten by the version in the "debug/sed" library, which can check the stack-effect diagram against runtime conditions.

TODO: -- (as of 20.08)

A comment word, which makes it easier to see items needing to be taken care of.

X n -- n (as of 22.04)

Inside loop , loop- , times return the loop index of the n th outer loop, counting from 0 for current loop. Returns 0 if an invalid loop index is given (e.g. if there is no such nested loop).

Note: the loop index is a singleton, so if you want to store it, clone it first.


See also: G:I G:J G:K
** --
IMMEDIATE

Comment to end-of-line: everything after the "\\" is ignored.


See also: G:SED: G:-- G:#! G:(*
_dup a b -- a a b (as of 21.03)

Same effect as over swap but faster and more efficient.

_swap a b c -- b a c (as of 21.03)

Same effect as rot swap but faster and more efficient.

actor: x w --
IMMEDIATE
needs utils/actor

Similar to a var, but an "actor" takes an item x as its value, and a word w to invoke. As with var, the is taken from the input stream and is the name by which the actor is invoked. As of 18.04, 'actor:' is just an immediate wrapper around 'curry:'

again --
IMMEDIATE

Unconditional return to the most recent unpaired repeat . May only be used in compile-mode, throws an exception otherwise. May be stopped with ;; (which immediately exits the word), or break (which causes the loop to not repeat).

If no repeat was given, then it branches to the start of the most recently compiled word (started with with : or ( ). This is different from recurse in that it does not issue a call/ret, rather just jumps to the start, same as if there was a repeat as the first word compiled in.


See also: G:while G:repeat G:while! G:break G:break?
ahead -- (as of 17.10)
IMMEDIATE

Compiles an unconditional "jump" instruction at the current PC, to be resolved with G:then .

and T T -- T

Returns the boolean "AND" of the top two items on the stack.


See also: G:or G:not G:xor
apropos --
DEFFERED

Looks for any word whose description or name contains <text> and prints out the matching words' names.


See also: G:help G:words G:words/ app:opts
argc -- n

Returns the number of command-line arguments to the running program. Always 0 on mobile.


See also: G:args
args n -- s | null -- a

Returns the command-line argument number n to the running program. Numbering starts at 0 for the first argument, and accesses any items on the command-line which were not treated as options (by G:process-args ). A negative value of n counts from the end (e.g. -1 args returns the last argument).

A value of null returns an array of all the arguments.

Note: On macOS, Linux, and RPI, a 'backslash' on the command line is ignored unless the argument is enclosed in quotes. Forgetting that may lead to unexpected consequences.


See also: G:argc
array? x -- x T

Returns true if x is an array, false otherwise.

assert x --

Assert that the value x in TOS is "true", and quits with a message if it is not. If the value is a string, it is evaluated using eval and then TOS is checked. This allows you to assert that a condition at is valid at runtime, for example:

"100 over n:="  assert 
base n -- n'

Set the numeric base to the n and returns the previously active base. The base is set on a per-task basis, the default base is 10.


See also: G:decimal G:hex
base>n s n -- n' (as of 22.08)

Same as G:>n , but sets the numeric base to n first, and restores it after. So "FF" 16 base>n returns 255.


See also: G:>s G:>n
bi x w1 w2 -- w1(x) w2(x)
needs combinators/bi

Implementation of Factor's "bi" combinator. Invokes w1 and w2 on x, leaving the results.

bits -- n

Returns 32 or 64: the "bit-size" of the current build of 8th (not the OS native bit-size!)

break --

Flags the current loop or iterator to stop at the next iteration point. Does not leave the loop or iterator at the point it is invoked! In addition, if invoked in interpret-mode, will cause the script being evaluated to stop evaluation at that point.

Affected loops: while , again , times , loop , loop- , times .

Affected iterators: m:each , a:each , s:each , b:each , b:each-slice , xml:each

Other affected words: a:map , a:filter , a:reduce , a:y , b:op , db:exec-cb , f:eachbuf , m:map , s:eachline f:eachline .


See also: G:break?
break? -- T

true if G:break was invoked.


See also: G:break
breakif x -- x (as of 20.08)

Same effect as dup if break then .


See also: G:break? G:break
build? -- s

Returns a string containing the OS/bits. e.g.: "LIN64" or the like.


See also: G:8thver? G:buildver? G:.ver
buildver? -- s

Returns a string of the 8th build version. e.g.: "6973156a" or the like.


See also: G:8thver? G:build? G:.ver
bye --

Quit 8th in the normal manner. The words in the onexit chain will be invoked in reverse order of their addition.


See also: G:die G:onexit
c/does x dw cw --
needs utils/create-does

Similar to ANS Forth "CREATE... DOES>". Takes an item x which is the default value, a word dw which is the "run-time" behavior, a word cw which is the "create-time" behavior and a string which is read from the input stream. It creates a new word called , which is itself used to create new words. Those new words it creates will invoke the cw word when they are created, and the dw word when they are run. In the case of dw, it is passed a clone of the item x. In the caes of cw, it is passed an array which contains the item x as well as the dw word. Thus, the cw word may modify the value or the action taken at run-time.

case s table -- | n table -- | table s -- | table n -- (as of 16.12)

Similar to G:caseof , but takes a number or string, and an array or map table . The table consists of (key,value) pairs where the value is a word (or [value,value...] if an array). If the key exists in table , its value is invoked. If not, nothing happens. As with G:caseof , the parameters may be in reverse order as well.


See also: G:caseof
case: -- (as of 19.03)
needs utils/case

Begins a "case:... case;" block, similar to the C "switch" statement. Use with of: ... of; and default: ... of; to define the cases. Uses caseof internally, but provides a more "friendly" syntax.

caseof a n -- x | n a -- x | m s -- x | s m -- x

A "case" construct which takes an array or map, and a number or string, as appropriate. It looks up the value in the container, and then if x is:

  • a word: invokes it and leaves the result (if any) on TOS
  • not found: puts null on TOS
  • otherwise, puts x itself on TOS.

The order of the container vs scalar isn't important, thus eliminating the need to invoke swap .


See also: G:case
catch w -- x true | w --false (as of 20.05)

Invokes the word. If an exception was thrown, returns the exception and true ; otherwise just returns false . Use with caution, since exceptions are generally intended to be fatal errors. G:catch will install its own temporary t:handler (and thus it is per-task). A typical usage might be

' possible-thrower catch if    \ caught an exception...   handle-exception then 
chdir s --

Change the current directory.


See also: G:getcwd
clip> -- s

Returns the current contents of the system clipboard.

clone x1 -- x1 x2

Create a "clone" x2 of the item x1 . Like dup , a "clone" has the same value as the original, but it is not the same actual item.

Modifying the clone does not change the value of the original item x . If x1 is a container type, all the contained items are also cloned.

Note: some item types cannot be cloned: "db", "sql", "hw", and "X".


See also: G:clone-shallow G:same? G:dup
clone-shallow x1 -- x1 x2

The same as G:clone , except that if x1 is a container type then the items contained are not cloned. That is, a shallow-clone of a container creates a new container with the same actual items as the original.


See also: G:clone G:dup G:same?
cold --

The default system startup, begins the interpreter loop.

compile w --
IMMEDIATE

Compiles an invocation of the word into the word currently being compiled. When that word is subsequently invoked, the word w will be invoked at that point.


See also: G:literal G:compile?
compile? w --
IMMEDIATE

Same as G:compile , except it only compiles if 8th is in compile mode; otherwise, it invokes the word w .


See also: G:literal G:compile
compiling? -- n (as of 19.03)

Returns non-zero if 8th is currently in "compile mode", 0 otherwise.

conflict s -- T
DEFFERED

Determine how 8th responds if a new word or other named item already exists in the current namespace. It is passed the name of the conflicting item, and returns true to permit it to be created, or false to disallow it. The default 8th behavior is to permit overwriting of existing items, but to warn that it is occurring.

const x1 -- x2

Equivalent of clone nip , used to ensure a copy of a container is used rather than the original. Generally used in the case where a container item is compiled into a word, and the container itself is not to be modified.


See also: G:clone
constant x -- (as of 19.01)

Creates a "constant" value. This is essentially syntactic sugar for the prior method of creating a new word containing the value x . Upon invocation of the name, x is on TOS.

container? x -- x T (as of 19.01)

Returns true if the item x is a "container", e.g. a type which contains other items.

counting-allocations T -- (as of 19.04)

If T is true , causes allocations of new items to be counted. This makes the G:.stats word return proper information. The default is false , meaning items are not counted when allocated.


See also: G:.stats
cr --

Print an OS-specific 'newline' sequence.


See also: G:. G:puts G:putc s:strfmt G:space
critical: -- (as of 23.09)
IMMEDIATE

Begins a "critical section" within a word. Locks that section of code so that another task cannot execute it simultaneously. May not cross word boundaries and must be paired with G:critical;


See also: G:critical: G:lock G:unlock
critical; -- (as of 23.09)
IMMEDIATE

Ends a "critical section" started with G:critical: .


See also: G:critical: G:lock G:unlock
curlang -- v

A var containing a string determining the current language used by s:intl etc. The default value is "en", for English. It should be set by the appropriate "lang/xx" asset.


See also: s:intl s:lang
curry x w -- w' (as of 18.04)

Returns a new anonymous word which takes a parameter x . Encapsulates w(x) as w' .


See also: G:curry:
curry: x w -- w' (as of 18.04)

Same as G:curry , but creates a named word.


See also: G:curry
decimal --

Set the numeric base to 10. Equivalent to 10 base drop .


See also: G:base G:hex
default: -- (as of 19.03)
needs utils/case

Used with G:case: to enumerate the default case.

defer: --

Create a deferred word <name> . This new word initially does nothing (its action is G:noop ). Assign it an action using w:is , remove an action with w:undo .


See also: w:undo w:is
deferred: w -- (as of 20.02)

Just like G:defer: except that it assigns the word w as the action of the newly created deferred <name> .


See also: w:undo w:is G:defer:
deg>rad n -- n'

Converts from degrees to radians.


See also: G:rad>deg
depth -- n

Current depth of the data-stack, e.g. the number of items it contains (before pushing the depth to TOS).

die n --

Stop 8th abnormally, with n as the program's return code. The words in the onexit chain will be invoked in reverse order of their addition.


See also: G:bye
dip a b w -- w(a) b
needs combinators/dip

Implementation of Factor's "dip" combinator. Invokes w on the items in position 2 (etc.) on the stack, moving the item in position 1 out of the way and restoring it afterwords to TOS.

drop a b -- a

Drop the item on TOS.


See also: G:dup G:2drop
dstack -- st

Returns a reference to this task's "data-stack", similar to G:rstack .


See also: G:rstack
dump x --

Do a hex-dump of the contents of the item x . Exactly what information is dumped depends on the type of x .

dup x -- x x

"duplicate" the item on TOS. This makes an additional reference to that item, it does not create a separate copy. If you wish to make a separate copy, use G:clone .


See also: G:dup? G:clone G:drop
dup>r x -- x

Duplicates TOS and pushes it onto the r-stack. Same effect as dup >r but faster.


See also: G:r> G:r@ G:rswap G:rdrop
dup? x -- x x | null -- null

Duplicate the item on TOS if and only if it is not null .


See also: G:dup
e# T -- (as of 20.04)

If true , numbers will be printed using scientific notation. The default is false . As with the other formatting words, this only affects the task in which it is invoked.

else --
IMMEDIATE

Begin alternate branch in a if... else... then block. May only be used in compile-mode, throws an exception otherwise. Also throws an exception if there was no accompanying if .


See also: G:if G:then
enum: startfrom ... enum; --
needs utils/enums

Create an "enumeration", e.g. words which return a numeric (increasing) value. Give a value to start from, and each name thereafter becomes a new "enum" -- up until the word "enum;', which ends the sequence.

error? -- n (as of 19.02)

Returns the task-specific errno. A non-zero value means something is amiss.

eval s --

Interpret the string (or buffer) as if it were typed into the interpreter. If s is null , nothing happens.


See also: G:eval!
eval! s -- T

Same as G:eval , but will not throw exceptions if evaluating the string would cause one. Instead, returns a true if no exceptions would have been thrown, false otherwise.


See also: G:eval
eval0 s -- (as of 17.08)

Similar to G:eval but ensures the system is in "interpret mode" prior to evaluation. The mode is reset to what it was originally.


See also: G:eval
exit n -- (as of 24.06)
IMMEDIATE

Causes a return of n words from the current word. So 1 exit is the same as ;; (and it's the implementation of it). Note: if there are fewer than n items on the system's return-stack, will throw an exception.

expect a x -- a flag
needs utils/expect

Tests the >kind of a against the number or array of numbers x. If a is not one of the listed types, puts false on TOS otherwise, puts true on TOS. In either case, the original item a is left under TOS.

extra! x x' -- x (as of 18.03)

Sets the item y as "extra" data associated with the item x .

Note: An item may not be associated with itself.


See also: G:extra@
extra@ x -- x x' (as of 18.03)

Gets any "extra" data associated with a particular item. Any item may have "extra" data associated with it. If no item is currently associated with x , null is returned.


See also: G:extra!
false -- T

Returns the boolean value false .


See also: G:true
fnv s -- n

Returns the FNV1a hash of the given string.

fourth a b c d -- a b c d a (as of 17.08)

Copies the fourth item on the stack to TOS. Same as 3 pick .

free x -- (as of 17.08)

Frees the item x by repeatedly decreffing it until it has a zero refcount. This should not normally be used, but is useful in some cases.

func: param s

Create a word called <name> which will invoke the external function s from the G:lib created library last invoked when creating the function.

At runtime, the parameter string param will be used to convert 8th types from the stack to native and vice-versa. Parameters are in the order expected by the external function (from low to TOS on the stack) and may also be given in an array.

The parameter string contains the return value as its first character, followed by one character for each parameter to the function, with a maximum of 12 parameters total.

Please view the manual's chapter on FFI for a complete description of the parameters.


See also: G:lib w:cb
getc -- n
DEFFERED

Read one character from the input (standard input or console) and return as a number n . Default behavior is G:(getc) .


See also: G:gets G:(getc) con:accept con:accept-pwd
getcwd -- s

Returns the current working directory.


See also: G:chdir
getenv s -- s'

Returns the value of the environment variable, or null if the variable doesn't exist.


See also: G:setenv
gets -- s
DEFFERED

Read from standard input or the console, up to a newline and return a string s . Default behavior is G:(gets)


See also: G:getc G:(gets) con:accept con:accept-pwd
goto n -- (as of 24.06)
IMMEDIATE

Compiles a non-returning jump to the 8th code address n . Used by G:recurse . If n is not in the range of valid 8th addresses, fails.

handler x -- T
DEFFERED

Handle an exception. Receives item x which describes the exception (usually a string, but you can throw any item type); return true to continue or false to quit. The default is to quit.


See also: G:throw
header s --

Creates a new dictionary entry named s whose code is left unfilled, and does not change to compile mode.


See also: G:: G:( G:(:)
help --
DEFFERED

Looks for any word <name> and prints out the documentation for it to the console. The name matching is case-sensitive. The default width of the output is 132 (or fewer) characters, or the width of the terminal, whichever is smaller. You can set the maximum by setting the "help.width" key using app:opts .

If a fully-qualified name is given, only that word's help is shown. Otherwise, all matching words' help is shown.


See also: G:apropos G:words G:words/ app:opts
help_db -- v
needs utils/help

Variable containing the name of the help database.

here -- n (as of 24.06)

Returns the execution address/token to be compiled next.

hex --

Sets the numeric base to 16. Equivalent to 16 base drop .


See also: G:base G:decimal
i: --
IMMEDIATE

Immediately cause the action of the next word. Ensures the next word is run immediately rather than compiled in. Only use on non-"immediate" words.


See also: G:p: G:l: G:i;
i; --
IMMEDIATE

When used instead of ; , marks the word being compiled as being immediate, e.g. one which is immediately invoked rather than compiled, and terminate the word's compilation just as ; does. Must be paired with : .


See also: G:p: G:l: G:i: G:;
if --
IMMEDIATE

Begins a conditional if... else... then block. At runtime, examines (and consumes) TOS. If it evaluates true , the code immediately following the if is run, until the matching else or then .

Otherwise, the code after the else or then is run. May only be used in compile-mode, throws an exception otherwise. Must be accompanied by then .


See also: G:else G:then
if; x --

If x evaluates true , exit the current word; otherwise, continue execution. Used within a word instead of the phrase if ;; then .

isa? x n -- x T

Returns true if x is an item from the given namespace identifier, false otherwise. Ex: to test if TOS contains a heap you could use ns:h isa? .

items-used -- n
needs utils/stats

Returns an array of arrays, each containing the name of the namespace and a count of how many items of each namespace have been used.

jcall X a -- x

Takes an X returned from G:jmethod , and an array of parameters to pass to the method. Makes the function call with the given parameters, and returns the type of data specified in the parameters list of the jmethod .

Note: Android only!


See also: G:jclass G:jmethod
jclass s -- X

Returns an X given a string containing the fully qualified name of a Java class (such as "java.lang.Thread"), which may be passed to G:jmethod to create a method by which one may call that method using G:jcall .

Note: Android only!


See also: G:jmethod G:jcall
jmethod X name params -- X'

Takes a string containing the name name of a Java method in a Java class previously returned from G:jclass . The params string follows the JNI specification and must match the signature of the Java method exactly. The returned item can then be passed to G:jcall . Please refer to the manual for a complete description of how this is used.

Note: Android only!


See also: G:jclass G:jcall
json! ma s x -- x (as of 20.04)

Analogous to G:json@ , but sets the item(s) at the JSONPath s to the value x . If that is a word, then it is invoked with the current value of the item at the path, and the result it leaves on TOS replaces the current item. Its SED is x -- x' . See the manual chapter 11.7 for details of the JSONPath syntax.


See also: G:json@
json-8th> sb -- x (as of 20.03)

Takes a JSON string or buffer and converts it to an equivalent of the original item given to G:>json . null on TOS will result in null . Unlike G:json> , this handles 8th JSON enhancements.


See also: G:>json G:json>
json-nesting n -- (as of 17.08)

Sets the limit of nesting JSON when converting items to a string. This affects >s and .s among other things. The default value is 100, which should be sufficient for most uses.

json-pretty n --

Tell the >json and other JSON output words to pretty-print JSON so it is easier for humans to read. A value of 0 means don't pretty-print; any other value is the number of spaces to indent each nested level. Legal values are between 0 and 16.

json-throw T -- (as of 18.04)

If true , then conversion of a self-referencing JSON to a string will throw an exception. Otherwise, the item will show as in the output string. The default is to not throw.

json> s -- x

Take a JSON string (or buffer containing JSON) on TOS and convert it to an equivalent of the original item given to >json . null on TOS will result in null .

Note: 8th-specific enhancements to JSON are not permitted for security reasons, and will appear as null in the returned item. If you have trusted JSON with 8th enhancements which you want to restore, use json-8th> instead, or perhaps eval .

Note: Using eval does pose a security risk if the string it is given is not from a trusted source.


See also: G:>json G:json-8th>
json@ ma s -- ma x true | ma s -- ma false (as of 20.04)

Accesses elements from the map or array using a subset of "JSONPath" syntax, returning false if the element does not exist, or true and the element x . See the manual chapter 11.7 for details of 8th's JSONPath syntax.


See also: G:json!
k32 -- n

Windows only: Returns the lib handle of the "kernel32" system library.

keep a b w -- w(a,b) b
needs combinators/keep

Implementation of Factor's "keep" combinator.

l: --
IMMEDIATE
needs utils/latebind

Makes the next word "delayed lookup". Compiles the string <name> into the word currently being compiled. At runtime, every time the code is invoked, it looks up the word with that name. So l: + will add two numbers, or concatenate two strings, using the same code.


See also: G:p: G:i:
last -- w

Returns the last word compiled.

lib s -- | a --

Create a word named <name> , which will load the external named library when invoked. At runtime, invoking the created word has the SED -- X returning an item representing the loaded library's handle, or null if it was unable to load it.

The library name s may be a complete name which is OS specific, such as "libiconv.so" or "iconv.dll". If just the base name is given, e.g. "iconv", then 8th will try to load "iconv", then "iconv.dll" (or .so or .dylib, depending on OS) and then "libiconv.dll" (etc). This makes writing cross platform library routines much easier, assuming the dynamic library has the same base name across platforms. That is, "iconv.dll", "libiconv.so" and "libiconv.dylib" in this example.

If an array is given (instead of a string), it should be an array of strings, which will be tried in the order they appear in the array. The first one to be a valid library on the system is used.

Sets t:err? if unable to load the library.

Ex: ["glib","glib-2.0"] lib glib .


See also: G:func: w:cb
libbin -- (as of 18.06)

Similar to G:needs , but creates a new word called <name> which causes, when invoked, that item from the 'libs' to be loaded as a buffer.

Ex: libbin fonts/generic.ttf creates a new word fonts/generic.ttf in the current namespace, which when invoked, will load the file "libs/fonts/generic.ttf" into a buffer.

It also flags the "build" utility that it needs to copy that library file into the asset folder so that invoking the new word in a packaged application will work properly.

Because this word is intended to allow you to incorporate binary data from libraries, it will silently ignore repeated invocations with the same name.


See also: G:needs
libc -- n

Linux, RPI and macOS: Returns the lib handle of the "libc" system library.

literal x --
IMMEDIATE

Compiles the item x into the word currently being compiled. When that word is subsequently invoked, the item x will be put on TOS.


See also: G:compile G:compile?
locals: -- (as of 17.06)
IMMEDIATE

Flags the word about-to-be-defined as using local variables. This is required if the word will use w:@ or w:! .


See also: w:@ w:!
lock x -- x

Acquire a lock on the item x . That means it will execute a tight loop until it can lock the item. If the item is already locked, it will "spin" forever until it acquires the lock. Locks are "advisory", meaning that they do not prevent other tasks accessing the item unless they cooperate and also use the locking facilities.


See also: G:unlock G:locked? G:lock-to
lock-to x n -- x T

Same as G:lock , but takes a timeout value as a whole number n of milliseconds. If that many msec pass without being able to acquire the lock, it returns false ; otherwise it acquires the lock and returns true .


See also: G:unlock G:locked? G:lock
locked? x -- x T

Queries the lock state of the item x , returning true if it is currently locked or false otherwise.


See also: G:unlock G:lock-to G:lock
log s --

Prints to the "log". That will be the controlling terminal, in a console app (or one which has a console), and to the system log facility (unless false log-syslog was invoked). Logging is performed on a separate task.

log-syslog T -- (as of 21.02)

If false , prevents G:log from also logging to the system log facility.

log-task T -- (as of 18.07)

If T is true , makes the G:log word print the task invoking it.

log-time T -- (as of 17.08)

If T is true , makes G:log print the time when it was invoked (the actual printing of the log message is asynchronous).

log-time-local T -- (as of 18.01)

Makes G:log print the time it was invoked in the local time, if true ; otherwise, it will use GMT. The default is local (e.g. machine) time.

long-days -- v

A var containing a map, mapping language names (e.g. "en") to an array of long names of the week-days. The default contains the English names of the week-days. It may be set using the appropriate "lang/xx" asset.


See also: s:intl s:lang G:curlang G:long-months G:short-days G:short-months
long-months -- v

A var containing a map, mapping language names (e.g. "en") to an array of long names of the months. The default contains the English names of the months. It may be set by the appropriate "lang/xx" asset.


See also: s:intl s:lang G:curlang G:long-days G:short-days G:short-months
longjmp n -- (as of 20.01)

Performs a non-local jump to the word given to G:setjmp . The number must be one returned by G:setjmp .

Note: you can only do a non-local jump within the same task!


See also: G:setjmp
lookup m s -- x | a n -- x | s m -- x | n a -- x (as of 20.08)

Same as G:caseeof , but does not try to dereference a word from the container.


See also: G:case G:caseof
loop w low hi --

Invoke the word w , hi - low + 1 times, counting up from low to hi , inclusive. The SED of the invoked w is n -- , where n is the current iteration number. If low is greater than hi , no iteration will occur.

Note: the loop index is a singleton, so if you want to store it, clone it first.


See also: G:times G:loop- G:repeat G:while
loop- w low hi --

Same as G:loop , but in the reverse direction, e.g. from hi to low .

Note: the loop index is a singleton, so if you want to store it, clone it first.


See also: G:times G:loop G:repeat G:while
map? x -- x T

Returns true if x is a map, false otherwise.

mark x T -- x (as of 18.05)

If true , flags the item as "marked", otherwise removes the flag. Useful for keeping track of whether an item has been seen or used.


See also: G:mark?
mark? x -- x T (as of 18.05)

Returns the "marked" flag of the item.


See also: G:mark
mobile? -- T

true if running a mobile platform, false otherwise.

n# n --

Set the accuracy, e.g. the number of significant digits kept after certain big floating-point calculations. It affects at least: n:sqrt , n:exp , n:ln , n:sin , n:cos , n:tan , n:asin , n:acos , n:atan , n:atan2 , n:^ . Default is 32.


See also: G:##
name>os s -- n
needs utils/os-names

Convert an OS name to an os value.

name>sem s -- x (as of 16.11)

Returns the semaphore of the name created by G:sem , or null if it doesn't exist.


See also: G:sem>name G:sem
ndrop a1 a2... aN N --
needs stack/utils

Drop 'n' items from the data stack

needs --

Parses the white-space-delimited string <name> , and evaluates the file it references. The library is searched for in this order:

  1. in the "libs" asset, then
  2. app:datadir , then
  3. the directory pointed to by the "EIGHTHLIB" environment variable, then
  4. app:8thdir .

The file searched for may have no extension or ".8th". The preferred library naming convention is to omit an '.8th' extension (as all 8th's libraries are so named), but an '.8th' extension will be searched for if the no-extension version isn't found.

Notes:

  • only includes the library once.
  • throws an exception if it cannot load the library.
  • use G:(needs) if you require a library name having spaces in it.
  • if your library has a private word named lib-init then it will be invoked automatically by G:needs just after the library has been loaded.
  • any words in a private namespace are not-findable after the library has loaded.
  • the "with-list" is restored to what it was prior to invoking G:needs .
  • likewise, the current namespace.

See also: f:include app:asset G:.needs f:slurp G:private G:public G:requires
needs-throws -- v (as of 24.03)

Variable which, if true , means that needs throws if the needed library can't be loaded. Defaults to true .

needs[ ] -- (as of 22.02)

Same as G:needs but operates on several libraries at once, e.g. needs[ lib1 lib2 lib3 ] .

new n -- x

Create a new item x from the given namespace number, which may be obtained by invoking the namespace name (for example, ns:n for a number). If n is not a valid identifier (that is, less than 0 or greater than the largest namespace identifier), then null is returned.

If the item being created is a "user-defined" item, e.g. from a namespace not built-in to 8th, then the word init is invoked with the new item on TOS. When refcounted to zero, the word deinit will be invoked prior to destruction.

next-arg -- x
needs utils/args-common

Gets the next argument after the currently processed one.

nip a b -- b

Drop the item under TOS.


See also: G:tuck G:drop G:dup G:swap G:over
noop --

Literally: "do nothing".

not T -- T

Convert true to false and vice versa. Interprets numbers which are non-zero as true for the purpose of this conversion.


See also: G:and G:or G:xor
nothrow w -- x (as of 20.05)

Invokes the word while forcing exceptions to be ignored. If there were any exceptions during the execution of w , the exception will be on TOS; otherwise null . This differs from G:catch in that exception handling is completely bypassed.

ns ns --

Make the namespace identified by the number or string ns the current one. If ns does not represent a valid namespace, nothing happens.


See also: G:ns:
ns: --

Use <name> as the current namespace. That namespace is the where new words will be created. The default namespace is user .


See also: G:ns
ns>ls n -- s

Convert the namespace identifier to its long string representation.


See also: G:ns>s G:ns G:ns:
ns>s n -- s | s -- s'

Convert a namespace identifier, to its short string representation. That is, it converts the number given by ns:n to the string s , or returns null if it does not correspond to a known namespace.

It may also be given a string, e.g. ns:n .

ns? -- s (as of 16.01)

Returns the name of the currently active namespace.

null -- null

Put the value null on TOS. This is an item whose value is indeterminate. It is often returned from words as a way of indicating there is no valid value to return.

null; x -- x | null --

If x is null , drop and exit the word; otherwise, continue execution. Used within a word instead of the phrase null? if drop ;; then .

null? x -- x T

Returns true if the item is null , or false otherwise.

nullvar -- (as of 22.07)
IMMEDIATE

Same as G:var but initializes the variable to null instead of 0 .


See also: G:! G:@ G:var
number? x -- x T

Returns true if x is a number, false otherwise.

of: x -- (as of 19.03)
needs utils/case

Used with G:case: to enumerate cases to be handled. Parses up to "of;" and evaluates that into a word for caseof

off v -- (as of 17.08)

Sets the var to the numeric value 0.

on v -- (as of 17.08)

Sets the var to the numeric value -1, equivalent to "all bits set".

onexit w --

Adds the word to the list of words to be executed, in reverse order, upon program termination.

only n --

Makes the namespace designated by the number n the only one which the interpreter will search for words. This should be used inside an application where you wish to give user access to eval under controlled conditions. If null is passed for n , then all namespaces are available again (that is, only is cancelled).

op! v w -- (as of 17.01)

Invokes w on the contents of the var, replacing its current contents. Any operands to w should appear in their normal stack order under v . Effectively the same as over @ swap w:exec swap ! .

or T T -- T

Returns the boolean "OR" of the top two items on the stack.


See also: G:and G:not G:xor
os -- n

Returns a number indicating the operating system:

n operating system
0 Linux
1 Windows
2 macOS
3 Android
4 iOS
5 Raspberry Pi

See also: G:os>name
os-names -- v (as of 17.01)

Returns a var containing an array of names of OSes 8th supports, in order of the return value of G:os .


See also: G:os
os>long-name n -- s
needs utils/os-names

Convert an OS value to the OS long name.

os>name n -- s (as of 16.12)

Returns a string corresponding to value as returned from G:os . Invalid values of will return null .


See also: G:os G:os-names
over a b -- a b a

"Duplicate" the item underneath TOS and make it TOS.


See also: G:2over
p: --
IMMEDIATE

Postpone the action of the next word. Ensures the next word is compiled, rather than run immediately. Only really affects "immediate" words.


See also: G:l: G:i: G:i;
pack a s -- b

Takes the items in the array a and packs them according to the format string s , returning a buffer with the binary representation of the packed array items.

If a is null , returns a buffer large enough to hold data as indicated by the format string s .

The format string may have any of:

fmt description
[0-9]* repeat count
b byte (as buffer)
B byte (as one-byte number)
c character (string)
d (8-byte IEEE) double
f (4-byte IEEE) float
h hex bytes (reverse hex dump)
i 4 byte integer
I BE i
l 8 byte integer
L BE l
p pointer to a string or buffer
P pointer (to a 'p' item: see ptr:pack - keep the ptr while its value is being used
s count byte (etc)
w 2 byte integer
W BE w
x ignore byte

Size overrides:

char description
- short int
= int
+ long int
& void *
\* use the full length of the buffer or string
: if present separates the "repeat count" from the "number of bytes" count

Ex: 3:2c means repeat a string of two bytes, three times


See also: G:unpack
parse n -- s | x -- s

Parse a string <text> from the input stream. If n is a number, then parse until the character whose ASCII (not Unicode!) value is 'n' is reached. If x is a string or a regex, parse until that string or regex is matched. The matched item is excluded from the resultant string.


See also: G:parsews G:parseln G:parsech
parse-csv m -- m (as of 20.01)

Takes a map with information about what kind of parsing to do. Keys are:

key type description default
cols n expected number of columns 8
comment n,s comment character if at start of line #
first w REQUIRED: opens or initialize the read, returns first line to parse
ffld T If true, first row is field names false
next w REQUIRED: reads next line to be parsed
quote n,s character used for quoting fields "
row w REQUIRED: invoked with result array for each row
sep n,s field separator ("," etc) ,

The "first" and "next" words have the SED m -- m s , and s may be null to indicate end of data. They may store information in the map which is the same one used to create the parser.

The "row" word has the SED m a -- m , where the array has string values. It is up to the application code to interpret the received values.

A line beginning with the "comment" character is ignored. "cols" is an optimization so 8th only allocates an array of the expected size (instead of a much smaller one, and then resizing).

If ffld is true , then the first row of the file contains the field names, which are then added as an array to the map passed in, using the key "fields" .

parse-date T -- (as of 22.08)

Controls whether or not the interpreter, if it fails to parse a number, attempts to then parse a date. The default is true , meaning that 8th will attempt a date parse if it fails to parse a number.

parsech -- s

Parse the next non-whitespace character from the input stream into a string one character long.


See also: G:parsews G:parseln G:parse
parseln -- s

Parse <text> from the input stream until the end of the line.


See also: G:parse G:parsews G:parsech
parsews -- s

Parse <text> from the input stream, skipping leading whitespace, until the following whitespace. The resultant string will not contain any whitespace.


See also: G:parse G:parseln G:parsech
pick n -- x

Duplicates the item x at position n in the stack, putting it on TOS.

TOS is 0, item under is 1, etc. If you try to pick beyond the limits of the stack, an exception will be thrown.


See also: G:over G:rot G:rpick
poke x y --
needs stack/utils

Pokes the value 'y' into postion x on the stack, numbered as TOS=0, before the parameters are added. So: 10 20 30 40 2 200 poke will give: 10 200 30 40.

pool-clear n -- (as of 17.03)

Walks the pool for the given namespace identifier, and frees the entire "free" list. This might be used, for example, after having used a large number of items (e.g. a big array of numbers) and releasing it. If you know the application will not require a similar number of items in the future, you can invoke pool-clear to release the memory used by those unused items.

pool-clear-all -- (as of 19.05)

Clears all pools in the current task. Same as G:pool-clear iterated over all the pools.

prior w1 -- w2

If a word with the same name as an existing word was created in the same namespace, this returns the prior version of that word, which would otherwise be inaccessible by name. If there is no prior word it returns null .

private -- (as of 18.05)

Puts the following words or vars in the #p namespace, which is intended for private use. When used in a library or file included using G:needs or f:include , the words or vars created in that private namespace will be invisible after that file is finished processing. That is, w:find will not find them.


See also: G:public G:needs f:include
process-args m --
needs utils/args

Pass it a map containing the argument name as a key, and the action to perform as its value, e.g.: { "-h" : ' do-help } If the action needs to grab the next argument to use, it should use next-arg to get the next argument to process. An argument which is not in the map will cause the processing to stop. All remaining (non-processed) arguments can be retrieved with **remaining-args ***. The processor of an argument can issue break which will stop further processing.

process-args-fancy m T -- m (as of 21.05)
needs utils/args-fancy

Pass it a map containing the argument name as a key, whose value is another map with 'cmd' -- the action to perform or 'var' -- the variable to put the 'nextarg' in also 'msg' -- help text to display if an unknown option is given.

The map's keys are entered into a trie so any unique initial prefix of options will work. The T value is true if you want the options to ignore case.

The following options are added unless they already exist: '--' 'stop processing' '-h' and '-?' 'display help'

The map returned contains any 'var' options processed.

process-args-help -- (as of 21.05)
needs utils/args-fancy

Invoke the default argument-processor's help screen, which displays help text based on the 'msg' key for each option.

prompt s -- s'
DEFFERED

word which returns the REPL's ok> prompt. The string it is passed contains spaces or one of the following: "\\"", "{", "[", or "+" to indicate which of those items is currently still open. It returns the prompt which will be displayed.


See also: dbg:prompt
public -- (as of 18.05)

Restores the namespace which was current prior to the previous G:private invocation.


See also: G:private G:needs f:include
putc n --
DEFFERED

Print the character n , which is a number representing the Unicode character to print. Default behavior is G:(putc) .


See also: G:puts G:. G:(putc)
puts s --
DEFFERED

Print the string s . Default behavior is G:(puts) .


See also: G:putc G:. G:(puts)
quote -- s
IMMEDIATE

Parses one character from the input stream, then parses the rest of the input stream up to the next instance of that character, returning a string. This is useful if you have embedded double-quotes, for instance. Note: the standard 8th "string-escapes" (for example "\n") are not processed by G:quote .


See also: G:"
r! x -- (as of 18.04)

Replaces the r-stack TOS with the data-stack's TOS item. Equivalent to rdrop</p> <blockquote> <p> r .


See also: G:r@ G:>r G:r>
r> -- x

Pop the item x from the r-stack and push it onto the data-stack.


See also: G:>r G:r@ G:rswap G:rdrop
r@ -- x

Pushes the top of the r-stack onto the data-stack, without removing it.

Note: this is not the same as r:@ , which is used to access a regex match!


See also: G:>r G:r> G:rswap G:rdrop
rad>deg n -- n'

Converts from radians to degrees.


See also: G:deg>rad
rand-jit -- n (as of 19.08)

Returns a random number from the "Jitter RNG".


See also: cr:rand G:rand-pcg
rand-jsf -- n (as of 19.08)

Generates a 64-bit pseudo-random number using the "JSF" PRNG.

rand-native -- n (as of 19.08)

Generates a 64-bit pseudo-random number using the OS-specific entropy provider. Not guaranteed to be available, cryptographically secure, or fast.

rand-normal mean sigma -- n (as of 19.08)
needs rand/normal

Returns a Gaussian "normal" distributed random number given a mean and standard-deviation sigma desired. How good the distribution is depends on the random number generator chosen.

rand-pcg -- n

Generate a 64-bit pseudo-random number using the "PCG" generator. This is much faster than cr:rand , but is not cryptographically random. The PCG state is task-specific and therefore task-safe.


See also: cr:rand G:rand-pcg-seed G:rand-jsf G:rand-jit
rand-pcg-seed n n2 -- | null --

Sets the 'seed' for the PCG PRNG to the given numbers. Using null instead will make the PRNG choose a random seed via cr:rand .


See also: G:rand-pcg
rand-range low high -- n (as of 19.08)
needs rand/range

Returns a random integer in the range [low,hi]

rand-select s -- (as of 19.08)
needs rand/util

Sets whether G:random is cr:rand, G:rand-pcg, G:rand-native, or G:rand-jit. The default is G:rand-pcg. The choices for s are:

"crypto" -- selects rand

"pcg" -- selects rand-pcg, the default

"jsf" -- selects rand-jsf,

"jitter" -- selects rand-jit, a very slow CPU-jitter based one, and

"native" -- selects rand-native, the OS-native entropy provider

randbuf-pcg n -- b

Generates a buffer of size n filled with pseudo-random bytes from the PCG random generator.


See also: G:randbuf
random -- n (as of 19.08)
DEFFERED

Returns a random number, initially from rand-pcg , for speed. Can be changed manually to another random number word, or you can use the rand-select word (from the library rand/util ) to set it symbolically.

rdrop --

Drop TOS of the "r-stack". Same effect as G:drop but for the "r-stack".


See also: G:>r G:>r G:r@ G:rswap
recurse --
IMMEDIATE

Invoke the last word created (e.g. G:last at the time this was compiled).

recurse-stack n -- (as of 17.05)

Set the "recursion stack size" (e.g. the hardware stack for return addresses). n must be a multiple of the system page size. Only takes effect for new tasks, not the main task.

ref@ x -- x n

Returns the "reference-count" n of the item x . This is what's shown when invoking .s .


See also: G:+ref G:-ref
reg! s x -- T

Sets the value of a Windows Registry key. The value may be a string, a number, or a buffer. Returns true if succeeded, false otherwise.

Note: Windows only!

reg@ s -- x

Gets the value of a Windows Registry key. Returns null if the value does not exist.

Note: Windows only!

regbin@ s -- b n

Get the value of a Windows Registry key, as a buffer containing whatever data is in the key, and a number which indicates the kind of item (the value for kind is the same as what the Windows RegQueryValueEx() returns). Returns null if the value does not exist.

Note: Windows only!

remaining-args -- v (as of 18.06)
needs utils/args-common

A var which contains an array of the remaining arguments to be processed. Once process-args has returned, contains arguments which have not been processed, either because break was invoked during processing, or because the argument was not known.

repeat --
IMMEDIATE

Begin a repeated block of code terminated with either again or while . May only be used in compile-mode, throws an exception otherwise.


See also: G:again G:while G:while! G:break G:break?
requires -- (as of 19.09)

Ensures that support for the required resources is loaded. "" is a space-separated string which may contain any of: nk snd con bt . The resource is only loaded once.

If the required resource isn't present (requires bt , if bt:init doesn't exist in the SKU or if it returns false ) then a message is thrown (because "requiring" means you really need that item to function).

The thrown message has an explanation of what exactly happened to cause a failure.

reset --

Remove all items from the data stack.

roll n --

Moves the item at position n in the stack to the TOS, and moves all other items down the stack; in effect, rotating the items. TOS is position 0, item under is 1, etc. If you try to roll beyond the limits of the stack, it will throw an exception.

2 roll has the same effect as G:rot . If ix is negative, roll takes the TOS and puts it at position ix , moving items up the stack. So -2 roll is equivalent to G:-rot .


See also: G:rot G:-rot G:rroll
rop! w -- (as of 18.04)

Invokes w on the TOS of the r-stack, using parameters from the data-stack, replaces its TOS.


See also: st:op!
rot a b c -- b c a

Move the item in the third position to TOS.


See also: G:-rot G:swap G:over G:drop G:nip G:tuck
rpick n -- x
needs stack/rstack

Returns the item at position n in the "r-stack". TOS is 0, item under is 1, etc. Same as G:pick , but for the "r-stack".


See also: G:pick
rreset -- (as of 23.08)

Equivalent of G:reset , but for the r-stack.


See also: G:reset
rroll n -- st
needs stack/rstack

Same as G:roll but for the r-stack.


See also: G:roll st:roll
rstack -- st

Returns an item which references the "r-stack". This permits you to operate on the r-stack using any stack word.


See also: G:dstack
rswap {x y -- y x}

Same as G:swap , but for the r-stack


See also: G:swap
rusage -- m

Returns a map containing the values of various resources used by the running program. Keys may be: "rss", "swap", "fault", "ixrss", "isrss", "load1", "load5", "load15", "idrss".

The meanings of the values are OS-specific.

s>ns s -- n (as of 18.08)

Returns the numeric id of the named namespace.

same? x y -- T

Compares the two items x and y for literal equality, e.g. whether or not they represent the same actual item. So:

  • 123 dup same? is true
  • 123 123 same? is false
  • 123 clone same? is false

See also: n:= s:=
scriptdir -- s

Returns the directory from which the script is running. Only applies when the script is sourced from the command-line, unlike G:scriptfile

scriptfile -- a

Returns an array containing the full path name of the script being run as well as scripts leading up to it (e.g. via f:include or G:needs ). It is empty if no script is run.

Index -1 is the currently running script.

sem s n -- X

Returns an named IPC semaphore, with an initial count of n . Returns null if it cannot create or open the semaphore.


See also: G:sem-post G:sem-wait G:sem-wait?
sem-post X --

Increments the count of the semaphore returned from G:sem , so another task or process using G:sem-wait can continue.


See also: G:sem G:sem-wait G:sem-wait?
sem-rm X -- (as of 18.08)

Removes the named semaphore (created by G:sem ) from the system. The actual removal will be deferred until all processes using it are finished.


See also: G:sem
sem-wait X --

Waits until the semaphore's count becomes non-zero, then continue.


See also: G:sem G:sem-post G:sem-wait?
sem-wait? X -- T

Returns true if G:sem-wait would succeed, false if it would block.


See also: G:sem G:sem-post G:sem-wait
sem>name X -- X s (as of 16.11)

Returns the name used when creating the semaphore with G:sem', or null` if it doesn't exist.


See also: G:sem G:name>sem
semi-throw T -- (as of 17.08)

If false , suppresses the exception probable missing ; or ) in ... which is thrown if a script file leaves the interpreter expecting more input. The default is true .

set-wipe sb -- sb

Sets "wipe" flag on a string or a buffer. That ensures that when the item's refcount has gone to zero, the data it holds is wiped before being released. This means the user does not have to manually use clear . Of particular use in cryptographic contexts.


See also: s:clear b:clear
setenv var val --

Set the value val of the environment variable var . If val is null , clears the value from the environment.


See also: G:getenv
setjmp w -- n (as of 20.01)

Creates a non-local jump point. The return value is a number passed subsequently to G:longjmp when it's desired to branch to the word.

Note: you can only do a non-local jump within the same task!


See also: G:longjmp
settings! key val --
needs utils/settings

Save the key,val pair in the settings database.

settings![] [key,val,...] --
needs utils/settings

Save the array of key,val pairs in the settings database.

settings@ key -- val
needs utils/settings

Get the setting named by the string 'key', and return its value or 'null' Note the use of the r-stack to transfer the result!

settings@? key default -- val
needs utils/settings

Get a settings value and if it is null, use 'default' instead.

settings@[] [key,...] -- [val,...]
needs utils/settings

Get the values corresponding to an array of keys in the settings database.

sh s w --

Execute the external command string, invoking the word w when the process has finished. If w is null , the app will not be informed when the command finishes. Execution is asynchronous. The SED for w is n -- , where n is the OS return code from the shelled process.


See also: I:sh G:sh$
sh$ s w --

Same as G:sh , except that the word w is given the string result from the shell invocation. The SED for w is n s -- , where n is the OS return code from the shelled process, and s is the string output (to stdout).


See also: I:sh G:sh
short-days -- v

A var containing a map, mapping language names (e.g. "en") to an array of short names of the week-days. The default contains the English names of the week-days. It may be set by the appropriate "lang/xx" asset.


See also: s:intl s:lang G:curlang G:long-days G:long-months G:short-months
short-months -- v

A var containing a map, mapping language names (e.g. "en") to an array of short names of the months. The default contains the English names of the months. It may be set by the appropriate "lang/xx" asset.


See also: s:intl s:lang G:curlang G:long-days G:long-months G:short-days
sleep n --

Sleeps the current task for that number of seconds, which does not have to be an integer. Fractional seconds are broken into milliseconds. A negative number means 'wait forever', or until t:notify wakes it up. So 1.5 sleep will sleep for approximately 1500 milliseconds.


See also: t:notify t:wait t:q-wait
sleep-msec n -- (as of 23.05)

Same as G:sleep , but n is milliseconds, and doesn't respond to wakes; will sleep the entire time it's given.

sleep-until d -- (as of 19.08)
needs utils/sleep

Sleep the current task until the date d. Contast with G:sleep which sleeps for a number of seconds. NOTE: will respond to t:notify by waking up perhaps prematurely.

slog x s -- (as of 21.02)

Same effect as s:strfmt log .

space --

Print a space character, ASCII 32.


See also: G:. G:cr G:puts G:putc s:strfmt
stack-check T -- (as of 16.13)

Determines whether or not type and bounds-checking are performed on stack operations. The default is true , and should only be changed once you have completely debugged your application.

stack-size n --

Sets the main data-stack size to the given number n . This is useful if you will need more than 128K items on the stack (but if you do need more than 128K items on the stack, you should probably reconsider your code!). It will not affect the data-stack size for callback words. The stack size for tasks is set using t:def-stack .

It also resizes the current task's data-stack and moves data if necessary to the resized stack.

step n --

Increment the current loop counter by n , which may be positive or negative. Works with loop and loop- , but not with times . Quits if the index is beyond the original loop limits.


See also: G:loop G:loop- a:map a:map= a:2map+ a:map+ a:each a:each! a:2each a:x-each a:x a:reduce+ s:map s:each s:each! b:each b:each!
sthrow x s -- (as of 20.05)

Like G:slog , but throws.

string? x -- x T

Returns true if x is a string, false otherwise.

struct: -- str
needs utils/structs

Begin definition of a "struct", which is actually a map containing field and type information about the struct. The struct ends with struct; .


See also: struct:struct;
swap a b -- b a

Exchange position of top two items on the stack.


See also: G:2swap G:rot G:-rot
tab-hook s -- a
DEFFERED

This is the word responsible for console tab-completion. It receives a string which is the text entered in the console before the TAB key was pressed. Returns an array of strings (possibly empty) matching the initial string.

This word is lazy-loaded on first use in the REPL, and is implemented in the utils/tab-hook library.

tell-conflict -- v

Returns a var which controls whether or not 8th will complain when overwriting an existing word. It contains true by default.

tempdir -- s

Returns the directory where temporary files will be created.


See also: G:tempfilename
tempfilename -- s

Returns a string suitable for a temporary file name in the directory G:tempdir .


See also: G:tempdir
then --
IMMEDIATE

Ends a conditional if... else... then block. May only be used in compile-mode, throws an exception otherwise. Also throws an exception if there was no accompanying if .


See also: G:if G:else
third a b c -- a b c a (as of 17.08)

Copies the third item on the stack to TOS. Same as 2 pick .

throw x --

Throw an exception. Quits the current word and passes x to handler . x may be any type: if it is a string it will be displayed as-is; otherwise, it will be converted to a string for display. If you throw a number, its value must be greater or equal to 1000. The default behavior prints a message, logs it to the system log, and quits the application, unless 8th is running from the console rather than a file or application.

In the latter case, 8th does not quit, on the assumption that you made a typo or other error, and the stack is left in an unpredictable state; so use reset or just ignore the stack state.


See also: G:handler
thrownull x y -- x

If x is null , then throw the item y . Otherwise, continue (with x on TOS). This should be used when a null result is a fatal error.

times w n --

Invoke the w n times. If n is zero or negative, w will not be invoked.


See also: G:loop G:loop- G:repeat G:while
tlog s --
needs debug/log

Same as log, but prepends a date-time stamp, including milliseconds, to the output.

toggle v -- T (as of 24.02)

Toggles the value in the var from true to false and vice-versa. Returns the previous value of the var.

tri x w1 w2 -- w1(x) w2(x)
needs combinators/tri

Implementation of Factor's "tri" combinator. Invokes w1 and w2 and w3 on x, leaving the results.

true -- T

Returns the boolean value true .


See also: G:false
tuck a b -- b a b

Duplicate the item on TOS under the item under TOS.


See also: G:nip G:drop G:dup G:swap G:over
type-check T --

If T evaluates false , prevents 8th from checking data types in the built-in words. This increases performance but also the risk of unexpected failures. The default is true , meaning items are type-checked by builtin words.

typeassert n1 n2 -- (as of 17.06)
DEFFERED

Invoked by the system when G:type-check is true and the type checking determines the types are not correct. Passed the namespace identifiers of the item and the expected namespace.

The default behavior is to throw an exception saying what is wrong, e.g. Expected %s but got %s . You can modify the behavior to check conditions and perhaps fix the parameters.

uid x -- x s (as of 21.03)

Returns a string uniquely identifying the item.

uname -- m (as of 19.03)

Returns a map with information about the system:

key description
machine hardware name
nodename machine name on local network
numpages total memory pages
numproc number of CPU cores
numproc_conf number of CPU cores configured
pagesavail available memory pages
pagesize system memory pagesize (usually 4096 or more)
proctype CPU version
release kernel version or Windows release
sysname OS name
uptime How long since the machine was rebooted
version kernel version or Windows release

Note: not all are available on every platform.

unlock x -- x

Release the lock on the item x . Note that any task can lock or unlock any item! That means that the locking model is cooperative, and you are responsible to make sure the task which locks is the same one which unlocks (or conversely, that another task doesn't unlock before testing the lock state).


See also: G:locked? G:lock-to G:lock
unpack sb s -- a n | sb n s -- a n

Takes the items in the string or buffer sb and "unpacks" them according to the format string s , returning the number of bytes processed, and an array containing the interpreted data from the buffer.

If a number is provided under the format string and above the buffer, it indicates an offset in bytes from the beginning of the buffer, from which to start unpacking. Format string same as for G:pack .


See also: G:pack
until x -- x (as of 18.03)

Same effect as not while .


See also: G:until! G:while G:while!
until! x --

Same effect as not while! .


See also: G:until G:while G:while!
var --
IMMEDIATE

Create a var named <name> , initialized with the number "0". Invoking the name will put the var on TOS; you can then retrieve data using G:@ or store data using G:! . Note that var as well as var, may only be invoked in interpret mode (that is, not inside a colon-def or anonymous word).


See also: G:! G:@ G:var,
var, x --
IMMEDIATE

Same as G:var except that the var is initialized with the value "x".


See also: G:! G:@ G:var
while x -- x
IMMEDIATE

At runtime, peeks at TOS; if true , returns to the most recent repeat .

Note: this does not pop TOS! If you want that behavior, use G:while! instead.

Only available in compile-mode, throws an exception otherwise. It also throws an exception if you forgot to invoke repeat before it. A "while loop" may be stopped with ;; (which immediately exits the word), or break (which prevents the loop from repeating).


See also: G:again G:repeat G:while! G:break G:break?
while! x -- (as of 16.02)
IMMEDIATE

The same as G:while , but pops x from TOS.


See also: G:while
with: --
IMMEDIATE

Add the namespace <name> to the "with list", which is the list of namespaces which will be searched. Matched by ;with . The namespace name should not have the "ns:" prefix, e.g. use with: n to add the number namespace to the with list.


See also: G:;with
word? x -- x T (as of 20.01)

Returns true if the item is a word.

words --
DEFFERED
needs utils/words

List all currently known words, alphabetically by ns

words-like s -- a | null -- a

Like G:words/ , takes a filter string, but returns an array of strings containing the fully-qualified names of words matching the filter. If s is null , returns all words.


See also: G:words/ G:words
words/ --
DEFFERED
needs utils/words

Like words, but matches only words which match the string "". If the filter ends with a colon, will only display words in that namespace

xchg x v -- x' (as of 17.03)

Puts the item x into the var v , and returns the item which it previously held.

xor T T -- T

Returns the boolean "EXCLUSIVE OR" of the top two items on the stack.


See also: G:or G:not G:and

Graph

Namespace: gr
Description: Graph data type: nodes, edges, weights

word sed/description
+edge gr n1 n2 n3 -- gr (as of 18.08)

Adds an edge to the graph. The parameters n1 and n2 are the numeric indices of the nodes (the indices are the positions in the nodes array of the particular node). n3 is the direction, as for gr:new , and if it is non-zero, then the 'directed' parameter of gr will become true .


See also: gr:+edge+w
+edge+w gr n1 n2 n3 n4-- gr (as of 18.08)

Same as gr:+edge , but lets you specify the weight as well. Using this word will override any "weight" word the graph would otherwise use.


See also: gr:+edge
+node gr x -- gr (as of 18.08)

Adds a node to the graph's list of nodes.

connect gr -- gr (as of 18.08)

Connects each node to every other node in the graph, creating an edge for each combination. If a weight word was set, it is used to determine the edge weight for each pair. If a threshold value was specified, then only edges with weights greater than (if above is true ) or less than (if above is false ) will be added to the graph.

edges gr -- gr a (as of 18.08)

Returns an array with all the edges of the graph. Each 'edge' is an array: [from, to, weight, direction].

Note: modifying the returned array will NOT modify the nodes in the graph; to do that, use gr:edges!

edges! gr a -- gr (as of 20.05)

Sets the edges of the graph. Each entry in the array must contain [from, to, direction, weight].

m! gr s x -- gr (as of 18.08)

Associates the value x with the key s in the graph.

m@ gr s -- gr x (as of 18.08)

Returns the value associated with the key s in the graph, or null if there is no such value.

neighbors gr ix -- gr a (as of 18.08)

Returns an array with all the nodes which share an edge with the node with index ix .

new m -- gr (as of 18.08)

Creates a new graph defined by the map. The keys in m can be:

key description
weight word comparing two nodes and returning a weight (defaults to no weight)
directed boolean (defaults to false )
nodes array of nodes (any 8th data item; defaults to nothing)
edges array of edge descriptors, which are each an array [start-edge, end-edge, weight, direction]
threshold number which the weight must be above (if "above") or below to include the edge
above boolean if true , the calculated weight must be above the threshold to include it
map map which has values specific to this graph
autoconnect boolean, if true connect up all nodes to each other

In the case of an unweighted graph, 'weight' is 0. 'direction' is 0 for undirected, 1 source->dest, 2 dest->source, 3 source<->dest.

m can also be null , to indicate an empty, unweighted, undirected, graph.

node-edges gr ix -- gr a (as of 18.08)

Returns an array with all the edges connected to the node with index ix .

nodes gr -- gr a (as of 18.08)

Returns an array with all the nodes of the graph, in the order inserted.

Note: modifying the returned array will modify the nodes in the graph, so be cautious.

traverse gr T ix w -- gr (as of 18.08)

Traverse the given graph starting at the "root node" given by the ix . If T is true, the traversal will be "depth-first", e.g. continue down child nodes as far as possible before searching sibling nodes. Otherwise, it will traverse siblings first.

The word w is invoked for each node visited, with a SED of gr x ix -- gr , where x is the node and ix is its index.

The traversal continues until there are no more nodes which can be visited, or G:break was invoked in w . After the traversal has completed, you may iterate the nodes list to see which have been traversed, by invoking G:mark? on the node.

weight! gr w -- gr (as of 20.08)

Assigns the word as the graph's weight function.

GUI

Namespace: g
Description: GUI Widgets and utilities

word sed/description
media? n -- s (as of 24.04)
needs gui/media

Returns one of the following values, if the value passed in (in pixels) is below the threshold (and above the preceding one). The values correspond to the media query values used by "Pure CSS", as expanded using typical display resolution standards.

Use the return value to decide UI layout parameters.

Hardware

Namespace: hw
Description: Hardware abstraction layer

word sed/description
arm? -- T

Returns true if running on an ARM CPU.

camera fmt -- hw

Takes an array from the "fmts" member of one of the camera maps returned from hw:camera? , and requests the use of that camera from the OS. Returns a hw representing the camera on success, or null if it could not get use of the camera.

camera-img hw -- hw img

Grabs an image from the camera hw, or null if no image was available.

Not currently on mobile.

camera-limits hw n -- hw a (as of 20.05)

Given a property from the enumerations in the "hw/camera" library, returns an array of the mininum, maximum, and default values for the property. If the property isn't available for the given hardware, or the camera has not been opened, returns null .

camera? -- a

Queries the system for information on available cameras. Returns an array of maps, one per detected camera. Because of "plug-n-play", the list of attached cameras may change, so it is necessary to invoke hw:camera? soon before hw:camera (unless one knows the camera list won't change in the meantime).

The map returned per camera has the "name", a "uuid", the camera's "index" in the original array, and an array called "fmts", which contains a list of the video resolution and formats the camera can produce. Each "fmts" array contains, in order, the format's width, height, "fourcc" format code, FPS, the camera index of the camera it belongs to, and the format index in the "fmts" *array.

cpu? -- m

Returns a map which identifies the properties of the CPU. Possible values returned:

key description
aes has "AES" instructions
avx has "AVX" instructions
avx2 has "AVX2" instructions
le Is the CPU "little-endian"
mmx has "MMX" instructions
neon has "neon" instructions
sse has "SSE" instructions
sse2 has "SSE2" instructions
sse3 has "SSE3" instructions
sse4.1 has "SSE4.1" instructions
sse4.2 has "SSE4.2" instructions
vendor "ARM" or "Intel"
device? -- s

Returns a string which is a description of the device on which 8th is currently running.

displays? -- n

Returns the number of displays (monitors) attached to this device.

displaysize? n -- wide high

Returns the dimensions of display number n : from 0 to (hw:displays? - 1), in pixels.

finger-match w to -- (as of 19.03)
Professional version

Takes a word and a number to , which is the seconds to allow for the system to scan fingerprints. "w" gets invoked with results (a map) containing a "msg" which is text explaining the value, and "code", a number which is 0 on successful match. If there is no hardware support, the code is -1; if the match times-out the code is -2; other codes are system specific. The callback is executed asynchronously.

Android only.

finger-support -- m (as of 19.03)
Professional version

Returns a map with two keys: "hw" is true if the device has fingerprint detection hardware, false otherwise; "prints" is true if fingerprints have been registered on the device.

Android only for now…

gpio n T -- X
Hobbyist version

Creates a new GPIO item which will be used subsequently for I/O on the GPIO pin n . If T is true , reads from the; otherwise write to it.


See also: hw:gpio@ hw:gpio! hw:gpio-mmap
gpio! X n --
Hobbyist version

Writes to the GPIO pin (returned from hw:gpio ). That value is evaluated as: anything which would be true evaluates as '1' (e.g. "on") and anything which would be false evaluates as '0'.


See also: hw:gpio hw:gpio@ hw:gpio-mmap
gpio-mmap n --
Hobbyist version

Determines how to access GPIO. If passed "0", it turns off the memory-map accessors for GPIO (the default is to use the OS accessors). If it is "1", it tries to use the Raspberry Pi specific memory-map accessors.

Note: If the hardware you are running on is not RPI, bad things might happen. You've been warned!.


See also: hw:gpio@ hw:gpio! hw:gpio
gpio@ X -- X m
Hobbyist version

Reads from the GPIO pin (returned from hw:gpio ) and returns null if it is unable to do so, or the value of the pin, which will be either '0' (for "off") or '1' (for "on").


See also: hw:gpio hw:gpio! hw:gpio-mmap
i2c bus addr -- hw
Hobbyist version

Given two numbers bus and addr , representing the bus-id and the device-address, returns a hw describing the opened I2C device, or null if it could not.

Note: this functionality is currently only available on Linux, Android, and Raspberry Pi, and requires "root" (or appropriate "group") access.


See also: hw:i2c@ hw:i2c@reg hw:i2c! hw:i2c!reg
i2c! hw b -- hw n
Hobbyist version

Writes the data in the buffer to the I2C device from hw:2ic . Returns the number of bytes written or null if there was a failure.


See also: hw:i2c hw:i2c@ hw:i2c@reg hw:i2c!reg
i2c!reg hw reg val T -- hw T
Hobbyist version

Writes the number val to the I2C device from hw:2ic register reg . If T evaluates true , writes one byte; otherwise writes a word (two bytes). The returned value T will be true if the data could be written, or false otherwise.


See also: hw:i2c hw:i2c@ hw:i2c@reg hw:i2c!
i2c@ hw n -- hw b
Hobbyist version

Reads n bytes from the hw returned from hw:i2c . Conversion of that data may be done with G:unpack , if needed. See hw:i2c for caveats regarding this word.


See also: hw:i2c hw:i2c@reg hw:i2c! hw:i2c!reg
i2c@reg hw reg T -- hw n
Hobbyist version

Reads from the hw returned from hw:i2c , at register reg . If T evaluates true , reads one byte; otherwise reads a word (two bytes). The returned value will be null if the data could not be read, or a number with the data otherwise.


See also: hw:i2c hw:i2c@ hw:i2c! hw:i2c!reg
isround? -- T (as of 18.06)
Professional version

Android wear OS only: returns true if the device has a round profile (e.g. a round-face watch). Otherwise (and on all other OSes) returns false .

iswatch? -- T (as of 18.06)
Professional version

Android: returns true if the device is a 'watch', or false otherwise.

mac? -- a

Returns this computer's network-cards' MAC addresses as an array of strings.

mem? -- n

Returns the amount of RAM installed as a number in MB.

model? -- s (as of 19.04)

Returns a string containing the model of the board (RPI etc); or null if unable to determine.

poll hw -- m

Poll the current state of the hw sensor hw , returning a map whose keys specify the data for that device. Ex: a "gps" device will return "lat", "lon" and "alt" keys, at least; and a "gyro" will return "x", "y", and "z"; and a "compass" will return "head" and "true". If the device is not available or has no data, null will be returned.


See also: hw:sensor
sensor s -- hw

Returns a new hw corresponding to the sensor type giving in the string s . Currently, that may be one of:

  • gps : GPS location
  • gyro : 3D attitude information
  • compass : Direction (N,S, etc)
  • accel : An accelerometer

Returns null if it failed to get that kind of sensor, or a hw item which may be polled, etc.


See also: hw:start hw:poll hw:stop
start hw --

Activate the hw sensor which was created using hw:sensor . Retrieve data from the sensor using hw:poll .


See also: hw:sensor
stop hw --

Stop the hw sensor from requesting updates from the hardware.


See also: hw:sensor
uid? -- s (as of 19.05)

Returns a unique hardware UUID, or null if that is not possible

Heap

Namespace: h
Description: Ordered container

word sed/description
+ h h2 -- h

Moves all items from the heap h2 to the heap h1 . Both heaps are modified.

clear h -- h

Remove all items from the heap.

cmp! h w -- h (as of 20.08)

Assigns the word as the heap's comparator function.

len h -- h n

Returns the number of items on the heap.

max! h T -- h (as of 19.06)

If T is true , sets the heap to return the "maximum" value (this is the default); otherwise, it will return the "minimum". This must be done before items are pushed into the heap, once it is created.

new w -- h

Create a new heap using the word w as the heap's comparator. The SED for w is x1 x2 -- n where n is negative if x1 is less than x2 , 0 if they're equal, and positive if greater.


See also: h:push h:pop h:peek
peek h -- h x

Like h:pop , but does not remove the item from the heap.


See also: h:pop h:peek
pop h -- h x

Returns the "largest" item x from the heap h while removing it, or return null if the heap is empty. The meaning of "largest" is determined by the heap comparator word passed it on heap creation.


See also: h:push h:peek
push h x -- h

Push the item x onto the heap.


See also: h:pop h:peek
unique h T -- h (as of 18.05)

If true , makes the heap "unique", which means that only unique entries will be accepted. In that case, pushing a non-unique item is a no-op. By default, heaps are "not unique".

html

Namespace: html
Description: html

word sed/description
parse s -- DOM (as of 21.09)
needs dom/html-parse

Parses a string containing HTML, returning a DOM

HTTP

Namespace: HTTP
Description: HTTP

word sed/description
>auth username password -- authstring
needs net/basic-auth

Given a username and password as strings, return another string which is an appropriately crafted string for "HTTP basic authentication".

Image

Namespace: img
Description: JPEG, PNG and BMP images

word sed/description
>file img s --

Write the image to a file named by the string s . s should have an extension of ".png", ".bmp", ".jpg", ".jpeg", or ".tga". 8th will save the image in the corresponding format. The default is PNG format if no extension matches. Sets t:err?

>fmt img n -- img' (as of 20.01)

Takes the source img and creates a new one with the given format. The number is one of:

  • 1: 256-color greyscale
  • 2: 256-color greyscale + 256 value alpha
  • 3: 256-color each RGB
  • 4: 256-color each RGBA
copy img dest src -- img (as of 18.01)

Similar to img:scroll , but copies a sub-section of the source img from src to dest . dest is an array of numbers which are: ["top","left"]. The src element is an array of numbers which are ["top", "left", "wide", "high"].

Note: the original img itself is modified!

crop img x y wide high -- img' (as of 16.12)

Returns a sub-image taken from the starting point (x ,y ) for a rectangle wide by high pixels. If the dimensions are outside the boundaries of the source img, returns null .

data img T -- img m (as of 17.03)

Returns a map containing:

key description
data a buffer with the raw pixel data
stride the "line stride", number of bytes between lines
pixstride the number of bytes between pixels
width the img width
height the img height
fmt a number indicating the img format:
0: unknown
1: 3-byte RGB
2: 4-byte ARGB
3: 1-byte

The T parameter should be true if you don't intend to modify the image data, false if you do.

desat img -- img' (as of 16.12)

Desaturate (convert to grayscale) the img.

draw img rect img2 -- img (as of 22.04)

Draws img2 within the rectangle on img .

draw-sub img pt img2 rect -- img (as of 22.06)

Draws the subimage at rect of img2 at position pt in img .

fill img clr -- img (as of 17.07)

Fill the img with the color.

fillrect img x y w h clr -- img (as of 20.01)

Fill the given img with the color within the rectangle, modifying the img.

filter img a -- img' | img m -- img' (as of 16.12)

Apply the convolution matrix defined by the array or map to the img. The array should have a size which is a perfect square; it will be treated as if it is (so if it has for example 10 numbers, the first 9 will be used to make a 3x3 convolution kernel). If a map is given, it must contain a key "mat" which is the matrix to use, and it may optionally contain the keys "mode" which is a number: 0 means ignore edge (the default); 1 = wrap edge; 2 = extend edge; 3 = treat edge as transparent black; and "normalize" which is a number to which the sum of the values in the matrix will be adjusted. So "normalize": 1 will make the matrix sum to 1 so that the overall brightness of the image is not affected.

flip img T -- img' (as of 16.13)

Returns an img which is the first one flipped end for end (mirrored). If T is true , then it flips horizontally; otherwise, if flips vertically.

from-svg sb -- img | m -- img

Loads an SVG image. If passed a string or buffer, then if it begins with "<" it is treated as SVG XML; otherwise, it is treated as the name of a file containing SVG.

If passed a map, then it may contain any of these keys (one of 'file' or 'svg' is required):

key description default
dpi Dots per inch 96
file Name of the file to read the SVG from
high Height of the image to create in pixels in the SVG
ofsx X offset to apply after scaling 0
ofsy Y offset to apply after scaling 0
scale Amount to scale the image by 1.0
svg Buffer or string containing svg
units Default image units ("px", "pt", "pc", "mm", "cm", "in") "px"
wide Width of the image to create in pixels in the SVG
line img x0 y0 x1 y1 clr -- img | img pt0 pt1 clr -- img (as of 22.04)

Draws a line on the image from pt0 to pt1 in the given color.

new s -- img | b -- img | img -- img' | wide high -- img

Load an img. Allowable formats are PNG, GIF, JPEG, and SVG.

If given a:

  • string: it refers to a file name
  • buffer: it is the raw image data
  • img: it is another image, in which case a copy of that image is made.
  • numbers: creates a new blank img wide x high pixels.
pikchr s class flags -- s w h | s class flags -- null (as of 22.04)

Parses "pikchr" code and returns a corresponding SVG string and its width and height, or null if the parse failed.

pix! img row col clr -- img

Set the pixel color in the image at (row,col) . The original image is modified.


See also: meta:color img:pix@
pix@ img row col -- img n

Returns the pixel color at (row,col)


See also: meta:color img:pix!
qr-gen sb n -- m (as of 17.07)
Hobbyist version

Generates a map with a QR-code from a string or buffer, with ECC level n . The map's keys are "size" and "data", where "data" is an array "size" X "size" of ones and zeroes describing the QR-code.

qr-parse img -- a | img -- n (as of 16.13)
Hobbyist version

Scans a black and white img for QR codes and returns null if there are none, or an array containing a string with the value encoded, or a number containing an error code. The possible error codes are:

  • 1: Invalid grid size
  • 2: Invalid version
  • 3: ECC format error
  • 4: Data error
  • 5: Unknown data type
  • 6: Data overflow
  • 7: Data underflow

See also: img:qr-gen
rect img x0 y0 x1 y1 clr -- img | img pt0 pt1 clr -- img (as of 22.04)

Draws a rectangle on the image from pt0 to pt1 in the given color.

rotate img n -- img' (as of 16.13)

Returns an img which is the first one rotated by n degrees.

scale img wide high -- img'

Resize the image to wide by high pixels.

scroll img n1 clr n2 -- img (as of 18.01)

Scrolls the source img, by moving the image data n2 rows or columns of pixels. n1 is the direction to move: 0 for 'up', 1 for 'right', 2 for 'down' and 3 for 'left'.

The clr parameter is the value which will be used to fill in vacated pixels. If it is null , then the color at the edge will be used to fill (for each row or column as appropriate).

Note: the original img itself is modified!

size img -- img wide high

Returns width and height of the image in pixels.

IMAP

Namespace: imap
Description: IMAP access words

word sed/description
fetch-full imap ix uid (r: arr) -- imap (r: arr)
needs net/imap

Fetch an IMAP message into the array on the rstack.

fetch-uid-mail imap uid -- imap result
needs net/imap

Fetch an IMAP message by uid.

login imap -- imap flag
needs net/imap

Log-in to the given imap. Returns true on success, or fail otherwise.

logout imap -- imap
needs net/imap

Log-out of the IMAP connection. After logout, the connection "hangs", so parse-response is not possible

new m -- imap
needs net/imap

Connects to an IMAP server using the options given in the map. Returns an 'imap' which is used for further communications:

  • debug: required boolean
  • port: number, if not given, defaults to 143 for IMAP with or without STARTTLS+IMAP or 993 for IMAP over SSL
  • pwd: required
  • secure: required string, one of 'none', 'tls', 'ssl'
  • server: required string, the name or ip address of the server to connect to
  • user: required
search imap s-query -- imap A
needs net/imap

Search IMAP e-mail and return array of e-mail objects.

select-inbox imap -- imap stats
needs net/imap

Returns the IMAP inbox as a map.

ISO

Namespace: iso
Description: Various ISO things

word sed/description
countries -- m (as of 18.06)
needs iso/countries

Returns a map containing (abbrev, name) pairs with the current ISO 3166-1 alpha-2 country codes and their expanded names and codes. Each two-character code (e.g. "US") key's value is a map containing at least "a3" (the alpha-3 code), "num", the ISO numeric code, "name" (the usual country name), "name2" (the "official" name if there is one) and "name3", the "common name", if there is one.

languages -- m (as of 22.03)
needs iso/languages

Returns a map whose keys are the two-letter ISO language names, and the contents are maps of (name, native); where 'name' is the English name of the language, and 'native' is the name of the language for native speakers.

JSON-RPC

Namespace: JSONRPC
Description: JSON-RPC access words

word sed/description
call rpc opts -- result
needs net/json-rpc

Make a JSON-RPC call.

Location

Namespace: loc
Description: Description of a location's information

word sed/description
bearing a1 a2 -- n (as of 24.03)
needs geo/bearing

Calculates the great-circle bearing between two geographic locations. Given two arrays containing [latitude,longitude] , returns the bearing in degrees from north, from location a1 to location a2 .

find loc --
needs geo/location

Find the given location loc by name. Tries both the English and Hebrew names. Returns a map with the location information, or null if it failed. The search is not case-sensitive.

sort hebrew? --
needs geo/location

Sort the locations collection by name. Use the Hebrew location name ("loch") for sorting if hebrew? evaluates true; otherwise, use the English name ("loc").

Map

Namespace: m
Description: Maps are unordered containers accessed by a string key

word sed/description
! m s x -- m | m n x -- m

Put the item x in the map or user-defined type using the indicated key. Normally, the key is a string; however, if it is a number it will be converted to a string first as if >s had been invoked on it.

If the key is anything but a string or a number, then the item itself will be used as a key, and that item will be returned with m:keys or m:each for instance. The string displayed then will start with "(item)". This allows using arbitrary items as keys in a map, but it is not JSON friendly.


See also: m:@
!? m s x -- m (as of 16.10)

Sets the value for the key, if there isn't already a value for that key.

+ m1 m2 -- m1

Insert the keys and their current values from map m2 into map m1 , modifying m1 .

+? m m2 -- m (as of 17.05)

The same as m:+ , but only adds those keys in m2 which are not already present in m .


See also: m:+
- m s -- m

Remove the key s and its associated item from the map m , modifying it.

<> m s1 s2 -- m (as of 22.07)

Swap the values of the keys "s1" and "s2" in the map. Ex: {a:12, b:54} "a" "b" m:<> returns {a:54, b:12} . Both keys must exist in the map.

= m1 m2 w -- m1 m2 T (as of 22.08)

Compares the two maps, using the word to determine equality. The maps are considered equal if they have the same number of keys, and each key's value is equal to the same key's value in the other map (including its type), according to the comparator word. That word's SED is x1 x2 -- T .

>arr m -- a (as of 21.03)

Converts the map into an array of [ [key1,val1], [key2,val2]...] . Inverse of m:arr> .


See also: m:arr>
@ m s -- m x | m n -- m x | m a -- m a'

Returns the item x in the map or user-defined type for the key, which is usually a string, but may also be any other item. If the key is a number, it is first converted to a string as if >s had been invoked on it. If the key is an array, it contains keys whose values in the map are returned in an array. If the key is any other kind of item, it is first converted to a string starting with "(item)" and looked up. If a key doesn't exist in the map, null is returned.


See also: m:!
@? m s x -- m x' | m a x -- m a' (as of 16.10)

Gets the value for the key in the given map, if it exists. If it doesn't exist, returns the default value x instead. If passed an array of keys, then x may be either an array of corresponding default values, or a single default value for all entries. If it is an array which has fewer items than the number of keys, the last item is used as the default for subsequent entries.


See also: m:@
[]! m s x -- m (as of 20.03)

Same as m:! , but if the key already exists, then if the existing value isn't an array, converts it to one and pushes the new value into it. Basically, accumulates values into an array for that key.

_! m x key -- m (as of 19.05)

Same as m:! , but with the key on TOS. More convenient in many cases.


See also: m:!
_@ m s -- x (as of 19.07)

Same as m:@ , but removes the map from the stack.


See also: m:@
_@? m s x -- x' | m a x -- a' (as of 24.03)

Same as m:@? but discards the map.


See also: m:@?
alias m s1 s2 -- m (as of 23.05)

Adds the key s2 to the map, pointing to the exact same item as s1 . Note: if s1 is subsequently modified, s2 will still refer to the original item (until it itself is modified).

arr> a -- m (as of 21.03)

Converts the array of [ [key1,val1], [key2,val2]...] into a map. Inverse of m:>arr .


See also: m:>arr
bitmap m a n -- n' (as of 19.09)

Given a map with keys whose values are numbers, and an array of strings which are some subset of those keys, returns the values ORed together in a single number. The n parameter is the default value to use if the keys aren't found, or if the array of keys was empty.

Ex: {a:1, b:2, c:4} ["a","c"] 0 m:bitmap returns 5.

clear m -- m

Remove all elements from the map.

data m -- m m'

Returns the internal map of a user-defined type. If m is not a user-defined type, returns null .

each m w -- m

Iterate over the map and invoke w for each element in it. The SED of w is key x -- ; that is, it is passed the key of the item as well as the item itself, and must consume both.

The map is not available on the stack while m:each is running, to avoid consistency problems. Modifying the map while it is being iterated may throw an exception.

exists? m s -- m T | m a -- m T

Returns true if there is a value defined for the key in the map or user-defined type m . This is necessary because requesting an arbitrary key from a map will always succeed, returning null if the key does not exist as well as if the value stored is actually null .

An array of strings may be passed, in which case each of them which must exist as a key with a value in the map for the return value to be true .

filter m w -- m' (as of 19.05)

Filters a map. The SED for w is s x -- T , where s is the key name and x is its value. If T is true , the item is kept; otherwise it is not.

ic m T -- m (as of 21.09)

If true , set the map to be case-insensitive with respect to key values. The default is false , and this must be set before any keys have been added to the map.

iter map keys wrd -- map
needs map/iter

Iterate over a map, in the order of the array of keys given. Do not iterate over any other keys. 'wrd' has the SED \ map key -- map

iter-all map keys wrd -- map
needs map/iter-all

Similar to m:iter, but first iterates over the keys in the given order, and then iterates over the remaining keys in alpha order.

keys m -- m a

Returns all the keys of the map m , as an array of strings.


See also: m:vals
len m -- m n

Returns the length of the map, e.g. the number of keys it currently contains. Equivalent to m:keys a:len nip .

map m w -- m'

Create a map whose elements are formed by invoking w for each element of the original map. The SED for w is: s x -- x' , where s is the key affected and x is the current value. The return value will become the corresponding element in the new map.

merge m1 m2 -- m1
needs map/merge

Merge the contents of m2 into m1. Iterates the keys of m2 (assumed to be maps), and merges into same key of m1, creating a map for the key, if needed

new -- m (as of 17.05)

Create a new, empty map.

op! m s w -- m | m a w -- m (as of 17.01)

Invokes w on the map's contents at key s or array of keys a , replacing the current contents. Any operands to w should appear in their normal stack order under m .

open m -- a1 a2 (as of 18.01)

Opens the map m , producing two arrays containing, respectively, the keys of the map and their corresponding values. Inverse of m:zip .


See also: m:zip
slice m a -- m' (as of 19.05)

Returns a map which is a "slice" of the original map consisting of the keys in the array. Items which don't exist will appear as null .

vals m -- m a (as of 18.04)

Returns all the values of the map, in the same order m:keys would give.


See also: m:keys
xchg m s x -- m x' (as of 18.04)

Stores a new value in the map at the key s , placing the current value on TOS.


See also: G:xchg a:xchg
zip a1 a2 -- m (as of 20.04)

Creates a map from two arrays, where a1 is the keys, and a2 is the values. All entries in a1 are processed. If a2 is shorter than a1 , the value null will be inserted as the value for the extra elements of a1 . Inverse of m:open .


See also: m:open

Markdown

Namespace: md
Description: Markdown text processing

word sed/description
2console s m -- f (as of 19.09)
needs md/2console

Takes an input string containing Markdown formatted text and writes to the console. Returns true if it was able to parse the MD

2html m s -- s (as of 19.09)
needs md/2html

Takes an input string containing Markdown formatted text, and a map with options, produces an HTML string as output. The map can have the keys: "css" (a string which is a file-name of CSS, or a buffer containing CSS; "num" - boolean which if true, means to number H tags; "frag" - boolean which if true means the HTML is not a whole document.

2nk m s -- f (as of 21.01)
needs md/2nk

Takes an input string containing Markdown formatted text and writes to the GUI. Returns true if it was able to parse the MD

Matrix

Namespace: mat
Description: Numbers: matrices (native double or complex, only)

word sed/description
! mat a n -- mat | n1 n2... nN n mat -- mat (as of 18.08)

Puts n into the matrix at the location specified by the array or the series of numbers, as with mat:@ .


See also: mat:new mat:@
* mat1 mat2 -- mat3 (as of 18.08)

Returns the result of a matrix-multiplication of the 2D input matrices. If the first matrix column dimension is not the same as the second's row dimension, null is returned.


See also: mat:new
+ m1 m2 -- m3 (as of 18.08)

Adds the input matrices. They must be of the same type and dimensions, otherwise the result is null .


See also: mat:new
= mat1 mat2 -- T (as of 18.08)

Returns true if the two matrices have the same dimensions and elements' values.


See also: mat:new
@ mat a -- mat n | n1 n2... nN mat -- mat n (as of 18.08)

Retrieves the value of the matrix at the position given by either the array or the numbers d1, d2... dN . In the first case, the size of the array must be the same as that of the matrix dimensions. In the second case, the number of numbers must equal the matrix dimensions.


See also: mat:new mat:!
affine a -- mat (as of 20.01)

Creates an affine-transformation matrix from an array of 6 numbers. If there are not 6 numbers, null is returned. Otherwise, a matrix is returned which can be used by mat:xform .


See also: mat:transform
col mat n -- mat' (as of 18.08)

Returns the column n from the matrix, giving a new 1D matrix as long as the number of rows in the original.


See also: mat:new
data mat -- mat a (as of 18.08)

Returns the data values of the matrix.


See also: mat:new
det mat -- n (as of 18.08)

Returns the determinant of the matrix. If mat is not 2-dim and square, returns null .


See also: mat:new
dim? m -- m a (as of 18.08)

Returns an array of numbers, the dimensions of the matrix.


See also: mat:new
get-n mat ix -- mat n (as of 18.08)

Gets the number or complex at offset ix in the internal representation of mat


See also: mat:new
ident n -- mat (as of 18.08)

Creates a 2D "identity matrix" of dimension n . The main diagonal is all "1" and the rest is all "0".


See also: mat:new
inv mat -- mat' (as of 19.02)

Returns the inverse of the matrix, or null if it is not possible to invert it. Does not currently handle inversion of complex matrices.


See also: mat:new
m. mat -- (as of 18.08)

Pretty-prints a matrix.


See also: mat:new
minor mat n1 n2 -- mat' (as of 18.08)

Returns the "minor" of the matrix, with column n1 and row n2 removed.


See also: mat:new
n* mat n -- mat (as of 18.08)

Performs scalar multiplication of n and the matrix. Modifies the original matrix.


See also: mat:new
new a1 a2 -- mat (as of 18.08)

Creates a new matrix, whose initial values are given in the array a1 (which may be null ), with dimensions given in the array a2 . If a1 contains fewer values than implied by a2 , the remaining values will be 0. This is the built-in version of mat:new , which only supports native double (real or complex numbers). The kind of value in such a matrix must be all of the same type, e.g. either numbers or complex numbers.


See also: mat:get-n mat:+ mat:dim? mat:same-size? mat:@ mat:! mat:n* mat:ident mat:row mat:col mat:trans mat:* mat:minor mat:det mat:= mat:m. mat:data
new-minor mat -- mat' (as of 19.02)

Returns the "matrix of minors" of the original, or null if that is not possible. The matrix of minors consists of the determinants of the minor of each position in the original.


See also: mat:new
rotate n -- m (as of 20.01)
needs math/affine

Returns an affine-transformation matrix rotating clockwise by n radians

row mat n -- mat' (as of 18.08)

Returns the row n from the matrix, giving a new 1D matrix as long as the number of columns in the original.


See also: mat:new
same-size? mat1 mat2 -- mat1 mat2 T (as of 18.08)

Returns true if the two matrices are the same size, false otherwise.


See also: mat:new
scale x y -- m (as of 20.01)
needs math/affine

Returns an affine-transformation matrix scaling (x,y)

shear x y -- m (as of 20.01)
needs math/affine

Returns an affine-transformation matrix shearing (x,y)

trans mat -- mat' (as of 18.08)

Transposes a 2D matrix with dimensions column,row into a new matrix with dimensions row,column.


See also: mat:new
translate x y -- m (as of 20.01)
needs math/affine

Returns an affine-transformation matrix translating (x,y)

xform pt mat -- a | a mat -- a' (as of 20.01)

Applies the affine-transformation matrix (created by mat:affine ) to the point or array of points.


See also: mat:affine

Network

Namespace: net
Description: Internet and sockets

word sed/description
! net key val -- net
needs net/utils

Insert a key,val into the opts map of a 'net'.

!? net key value -- net
needs net/utils

Same as m:!? for net

- net key -- net
needs net/utils

remove the key from the net opts

>base64url x -- s (as of 23.08)
needs net/base64url

Convert a buffer or string to "base64url" format

>url s -- s'

URL-encode the string as per RFC 3986.


See also: net:url>
@ net key -- net val
needs net/utils

Get the 'key' from the opts map of a 'net'.

@? net key default -- net val
needs net/utils

Same as net:@ but use the default if the key is empty

CGI -- T (as of 23.01)
needs net/cgi

true if running as a CGI script

DGRAM -- n

Returns a number to pass to net:socket to use a datagram (UDP) protocol.


See also: net:INET4 net:INET6 net:STREAM net:socket
INET4 -- n

Returns a number to pass to net:socket to use internet v4 addressing.


See also: net:INET6 net:STREAM net:DGRAM net:socket
INET6 -- n

Returns a number to pass to net:socket to use internet v6 addressing.


See also: net:INET4 net:STREAM net:DGRAM net:socket
PROTO_TCP -- n

Returns a number to pass to the net:socket word.

PROTO_UDP -- n

Returns a number to pass to the net:socket word.

REMOTE_IP -- s (as of 23.01)
needs net/cgi

If net:CGI , then the IP address of the client; otherwise null

REMOTE_IP -- s (as of 23.01)
needs net/cgi

Returns the IP address of the connecte client.

STREAM -- n

Returns a number to pass to net:socket to use a streaming (TCP) protocol.


See also: net:INET4 net:INET6 net:DGRAM net:socket
accept net -- net'

Waits for a connection on net after invoking net:listen . When the connection occurs, returns a new socket on which to talk to the remote side.


See also: net:bind net:listen net:connect
active? -- m (as of 23.03)
needs net/active

Returns a map with a key IPV4 and/or IPV6 pointing to a map with information from net:ifaces? for those interfaces which are not just loopback etc.

addrinfo>o X -- a

Convert the X returned from net:getaddrinfo into an array of maps (one for each addressinfo) with the keys:

key description
addr either null or a valid IPv4 or IPv6 address string
canon if present, a string with the canonical name of the address
family string, either "V4" or "V6"
flags number, various OS-dependent flags
proto number which is the protocol
type string, either "stream" or "dgram"
again? net -- net T (as of 17.01)

Returns true if the last read or write on net had an error of "EAGAIN", which means "try again in a while".

alloc-and-read net -- net buf|net null
needs net/utils

Allocates a suitable buffer, and reads from the net into it. Set the 'wait-to' value to the number of msecs to wait for input from the remote side (default is 1000)

alloc-buf net -- net buf
needs net/utils

Allocate a new buffer based on the 'bufsize' the user set. This is a buffer which can be used to read into for the net.

avail? -- T (as of 24.05)
needs net/avail

Returns true if there is internet connectivity, uses a DNS query to determine status.

base64url> s -- b (as of 23.08)
needs net/base64url

Convert a string from "base64url" format to a buffer

bind X net --

Binds the net to the X returned from net:getaddrinfo .


See also: net:connect net:accept net:listen
cgi-get s -- m (as of 23.04)
needs net/cgi

Parse input string as GET

cgi-http-header T -- (as of 23.04)
needs net/cgi

Control whether or not an "HTTP" header is output. Defaults true , but use false for normal CGI scripts.

cgi-init T -- m (as of 23.01)
needs net/cgi

Reads the CGI data. If T is true , allows GET data; otherwise, only POST. Currently, POST data must be JSON. Returns the URL requested, and a map of the request variables passed in.

cgi-init-stunnel -- s m (as of 23.04)
needs net/cgi

Like net:cgi-init , but for stunnel invoked scripts, where the GET or POST is in the stdin. Returns the URL requested and the parameters as a map

cgi-out mime charset data -- (as of 23.01)
needs net/cgi

Prints data as appropriate for a CGI response. If a buffer, converts to base64 first. 'charset' is usually "utf-8". "mime" might be "application/json" or whatever you need.

close net --

Close the net. It may not be read from or written to after this.


See also: net:socket
closed? net -- net T (as of 19.05)

Returns true if the net was closed by the other side; false otherwise.

connect X net --

Connects to the net with the X returned from net:getaddrinfo .


See also: net:bind net:accept net:listen
curnet -- net (as of 22.05)
needs net/utils

Get the net this task is handling

debug? net -- net T
needs net/utils

Determine if the user is wanting to debug the connection (prints RECV/SEND and data)

delete url -- opts buf true | opts false (as of 20.02)
needs net/http

Same as net:get, but with HTTP DELETE.

dns m -- m' (as of 24.02)

Makes a DNS query according to the values passed in the map.

Input keys are:

key type description
dns array Each entry is a dotted-ip address of a DNS server. At least one is required
host string The host to query the DNS about. Required
type string What type of record to get. One of A, MX, NS, CNAME, SOA, PTR, TXT, AAAA, SRV, OPT, SSHFP, SPF, or AXFR
fam number Either 4 or 6, for INET or INET6 (default: 4)
proto string Either tcp or udp (default: tcp)
class number Either 1=in or 255=any (default: 1)

The only required keys are 'dns' and 'host'. The others default as indicated (type defaults to A).

The returned map contains keys corresponding to the DNS packet's values. Generally, "QUESTION" and "ANSWER" will appear. The ANSWER key is an array of returned "pretty-printed" values.

get url -- opts buf true | false
needs net/http

Retrieve the web page given by the string or map url using HTTP GET. If successful, true is on TOS, and a buffer b with the retrieved data is below it, and the opts map with headers etc is below that.

If unsuccessful connecting, false is on TOS, and the net may have an "errmsg" in its opts (use "errmsg" net:@ to get it).

Note that true will be returned even if the item requested was not found on the server. It is the programmer's responsibility to check the "retcode" and "response" keys in the RAWHEADERS key of the returned opts map to validate the expected data were returned.

getaddrinfo addr service -- X

Given a string addr , representing an internet address (dotted-ip or name), and the number or string of a service (e.g. "http" or 80), returns an opaque X which is the address information for the given server. If null is passed as addr , it means "localhost". The return value is null if the lookup failed. Use net:addrinfo>o to parse the data in the X.

getpeername net -- net s n (as of 17.07)

Return the IP address string, and port number, for the connected net .

head url -- opts buf true | opts false
needs net/http

Same as net:get, but with HTTP HEAD.

ifaces? -- a (as of 17.08)

Returns an array containing one map for each network interface known to the system. Each map contains one or more of the following keys:

key description
addr IPV4 address
addr6 IPV6 address
cast broadcast address
desc description (Windows)
fname friendly name (Windows)
mac MAC address
mask netmask
name canonical name of the interface, e.g. "eth0"

It is not an error for some of these keys to be absent (in particular: "addr" and "addr6" are mutually exclusive).

ipv6? net -- net T (as of 23.03)

Returns true if the net is using IPV6.

launch s -- (as of 24.05)

"Opens" the URL given in a separate OS-specific process (browser).

listen net --

Given a net which has been bound to an address using net:bind , listens for an incoming connection. Blocks until the listen succeeds or times-out.

The default is to allow a backlog of 10 connections; you can set that by creating the socket with a map having the key backlog set to whatever value you want.


See also: net:bind net:accept net:connect
map>url s -- m (as of 20.03)
needs net/urlencode

Converts a map into application/x-www-form-urlencoded format so it can be transmitted in a POST request Inverse of net:map>url: converts urlencoded form to a map NOTE: all values are re-encoded as strings

mime-type s -- s s2 T (as of 23.05)
needs net/mime

Takes a file name and returns it and its "mime-type" (based upon file-extension) on TOS. If the type isn't recognized, assumes binary data. TOS is true if the type is binary (not text).

net-socket opts -- net true | false
needs net/utils

From the options, create a suitable 'net', open to that server and 'true', or just 'false' if unable to open a socket. Takes into account proxy settings.

opts net -- net m (as of 16.12)

Retrieve the map used to initialize the net, which is also known as the "options map" of the net.

port-is-ssl? m -- m
needs net/url

Given a parsed URL, determine the port to use and whether it's ssl.

post url -- opts buf true | opts false
needs net/http

Same as net:get, but with HTTP POST.

proxy! opts --
needs net/http

Pass a string like "abc.com:900", or a map like { "proxy-server" : "abc.com", "proxy-port": 900} to set the HTTP proxy parameters. You can also set a proxy on a per-connection basis by setting the proxy-server and proxy-port keys in the options map before making the connection.

put url -- opts buf true | opts false (as of 20.02)
needs net/http

Same as net:get, but with HTTP PUT.

read net s n -- net s n | net n -- net b n

Same semantics as f:read but for a net (e.g. a network socket).


See also: net:socket net:write net:close
read-all net n1 n2 -- net b (as of 19.05)

Similar to net:read , but continues reading until no more can be read or n1 bytes were received. If n1 is -1, there is essentially no limit. n2 is the number of milliseconds to wait for data; if that is exceeded, the receive stops. The returned buffer's size is the number of bytes received.


See also: net:read
read-buf net n -- net b (as of 22.04)

Same as f:read-buf , but for a net socket.


See also: net:read net:write
recvfrom net b n -- net X b n2 | net b n -- net null (as of 17.08)

Receive a message on the net into the buffer b . Returns the number of bytes received and an X which contains the ip address and port from which it received the message, if possible. If there was an error, null is pushed instead.

Note: The size of the buffer is not modified to reflect the number of bytes received.

s>url s -- m
needs net/url

Breaks a string s representing a URL into a map with the keys

  • "scheme" (string, e.g. "http")
  • "url" (string, e.g. "google.com"
  • "port" (number, e.g. 80)
  • "path" (string, e.g. "something/index.html)
  • "user" (string, e.g. "joe)

Missing values will be null, except for 'port' which may be set by 'scheme'. A URL may have the form: http://joe@google.com:80/index.html and some of the components may be missing.

sendto net X sb n -- net n' (as of 17.07)

Sends a message to another socket, with no guarantee of delivery. X is returned by net:getaddrinfo or net:recvfrom . sb is a string or buffer to send. n is normally 0, but may be MSG_OOB or other similar constants as defined by the OS. Returns the number of bytes sent or null if there was an error sending.


See also: net:getaddrinfo net:recvfrom
server m -- net

Creates a net which is a TCP server processing network requests. The default port number is 8080, if one is not provided using the key "port". The required key "recv" is invoked when a client connects, and is given a net which refers back to the connected client, as well as a buffer containing the data received (on TOS). It may use net:write to return data to the client using the net it was given, and must return false to continue receiving data or true to terminate the connection.

Valid keys are:

key type description default
addr s the IP address to bind to null
cert bs if TLS, the certificate to use
chunk n max number of bytes to receive at one time 16K
errcb w invoked if an error occured on the connection
key bs if TLS, the key to use
lost w invoked when connection was lost
made w invoked when connection is made
port n the port to listen to 8080
recv w invoked when data arrives
tls T if true, use TLS false
tlsver n 10,11,12, or 13 12
to n seconds before timing-out 1

If present, the "cert" and "key" keys contain either a file-name with a PEM certificate or private key, or a buffer containing them. An exception will be thrown if "tls" is true but "cert" or "key" are not present, or if "cert" or "key" are invalid.

The SED for made , lost , and errcb is net -- . The net in the lost callback is closed, or soon to be closed, so do not write to it or try to read the remote address (there probably isn't one).

The SED for recv is net b -- T

setsockopt net m -- net (as of 17.07)

Calls the 'setsockopt' function on the socket handled by the given net . The map is in the same format as for the "sockopts" key given to net:socket .


See also: net:socket
socket domain type -- net | m -- net

Create a new socket with the given parameters. domain is either net:INET4 or net:INET6 , type is either net:STREAM or net:DGRAM . null is returned on error.

You may instead pass a map, which will create an socket using "INET4 STREAM" as well as set the 'options' for further net activity to the map. You can change the defaults using the keys:

key description default
domain net:INET4 or INET6 INET4
proto protocol value 0
sockopts map with options as per net:setsockopt
type net:STREAM or DGRAM (or any value your OS supports) STREAM

See also: net:write net:read net:close
tcp-connect x -- net (as of 23.03)
needs net/connect

Takes a URL (including port, possibly) or a map with connection information, and attempts to create a TCP connection. Returns the connected net, or null on failure. Prefers an IPV6 connection over IPV4, but checks for that ability. If the map contains proxy-server and proxy-port , those are used instead of host and port .

tlserr net -- net s (as of 23.01)

Returns the TLS error string recorded for the last action on that net. Will return null if no error was recorded, or if the net isn't using TLS.

tlshello net m -- net T | net -- net T (as of 17.01)

Initiates a TLS connection over the. If the map is omitted, the options map given the net on creation is used. If the TLS handshake is successful, returns true otherwise return false .


See also: net:socket
udp-connect x -- net (as of 23.03)
needs net/connect

Same as net:tcp-connect but for a UDP connection. information, and attempts to create a UDP connection.

url> s -- s'

URL-decode the string as per RFC 3986.


See also: net:>url
user-agent s --
needs net/http

Sets the "user agent" which the HTTP library will use.

valid-email? s -- T (as of 22.04)
needs net/validemail

Checks a string for possible validity. It first checks for a single '@' character and if there is one, it assumes the part after is a domain, and checks for an MX record. If both those tests pass, true is returned; otherwise, false .

vpncheck ip apikey -- m (as of 21.08)
needs net/vpncheck

Given an IP address and your VPNAPI.io API key, returns a map containing information about the IP address. Keys returned are 'ip', 'security', 'location', and 'network' (as of 21.08, might change in future) Will return 'null' on failure.

wait net T n -- net T

Wait to see if the net net is ready. Will wait n milliseconds. If T is true , waits for incoming data to be ready; otherwise it waits for the underlying socket to be ready to write. Returns true if the net is ready, false otherwise. Does not actually read or write on the net.

webserver m -- net (as of 22.05)
needs net/webserver

A wrapper around net:server which processes incoming requests and handles them appropriately. The map has the same options as for net:server , but any recv member is overwritten. Additional options are for the callbacks to process specific request types:

get , post , head , put , delete , connect , options , trace , patch , ws-start , ws , ws-end , verb? .

The SED for every non websocket callback is net -- net T . The net has several items accessible with net:@ :

  • uri -- the requested page from the URL
  • verb -- GET/POST/etc.
  • rx-query -- Received "query string"
  • rx-header -- received HTTP headers ('Content-type', etc)
  • rx-body -- the received HTTP request body (after the headers) For ws the callback SED is net b -- net T where b is the raw buffer of data sent. , and the returned T is true to end the connection and false to leave the connection open. For ws-start the callback is net a -- net T , where true means "ignore" and false means "accept connection". For ws-end the callback is just net -- net , giving the app a chance to do cleanup (but not to close the net!).
write net s -- net n

Same semantics as f:write but for a net (e.g. a network socket).


See also: net:socket net:read net:close

Nuklear

Namespace: nk
Description: Low-level Nuklear Interface

word sed/description
(begin) m -- T (as of 20.01)

Starts a new window based on the map. It needs to be invoked every frame for every window (unless hidden), otherwise the window gets removed. Returns true if the new window can be filled with widgets, or false if not. You want to use nk:begin instead. Keys are:

key type description default
bg clr Color (or image) used to paint this window's background win
bounds rect Initial size and placement of window win
flags n Some combination of the nk_panel flags 0
font font The font to use for this window's elements win
name s A unique identifier for the window
padding pt Window padding [x,y] in pixels [0,0]
style m A "style" to use for this window.
title s A title for the window, and its identifier if name isn't given anon

See also: nk:(end) nk:get nk:set
(chart-begin) n1 n2 n3 n4 -- n

Starts a chart of type n1 , with n2 entries, minimum value n3 and maximum n4 . Returns non-zero if successful, 0 if failed.

(chart-begin-colored) n1 n2 n3 n4 clr1 clr2 -- n

Same as nk:(chart-begin) but using normal color clr1 and active color clr2 .

(chart-end) --

Ends a chart after nk:(chart-begin) .

(end) -- (as of 20.01)

Terminates a window definition started using nk:begin . MUST be paired with nk:(begin) .


See also: nk:(begin)
(group-begin) name title flags -- n (as of 20.01)

Starts a new group with internal scrollbar handling. Calls nk_group_begin_titled internally.

(group-end) -- (as of 20.01)

Ends a group. Should only be called if nk:(group-begin) returned non-zero.

(property) s min max step inc T v -- v (as of 20.01)

Creates a "property" control named s , with a minimum value, a maximum value, a step value, and an increment per pixel. T is true if the value in v should be an integer, false if it is a float (double).

>img -- img (as of 20.02)

Takes a 'snapshot' of the current screen window.

addfont font s -- (as of 20.01)

Adds the font to the current context with a name so it can be found by nk:push-font etc.

anti-alias T -- (as of 20.02)

Turns on anti-aliasing for lines and shapes. Default is true , meaning anti-aliasing is turned on.

any-clicked? rect -- T (as of 21.01)

Returns true if any button was clicked in the rectangle.

bounds -- rect (as of 20.01)

Returns the bounds of the currently active NK window

bounds! rect -- | null -- (as of 20.01)

Sets the bounds of the currently active NK window. If given null , sets to full-screen.

button m -- | label align img symbol style w --

Takes a map describing what the button should display (or a series of parameters):

key type description
align n One of the text alignment constants, if label is defined
cb w REQUIRED: The word to invoke when the button is pressed
img img An image to display
label s A text label
style m A style definition (see below)
symbol n One of the symbol constants

The "style" map, if present, is defined as follows. Default values are taken from the current context style:

key type description
bg clr,img What to display as the button normal background
bg-active clr,img The bg when the button is active
bg-border clr The color of the border
bg-hover clr,img The bg when hovering over the button
border n Border width in pixels
draw w Word to invoke for custom drawing
draw-end w Word to invoke after custom drawing
img-align n NK_TEXT_ALIGN... constant to align image in button
img-padding pt Padding around image in pixels
img-scale n Percentage of button height for image (<100)
padding pt Padding around text in pixels
rounding n Radius of corners in pixels
touch-padding pt Padding in pixels for touch resolution
txt clr The fg color of text
txt-active clr The color of text when active
txt-align n One of the text alignment flags
txt-bg clr The bg color of text
txt-hover clr The color of text when hovering
button-color clr w --

A button with the given color; invokes w when pressed.

button-label s w -- (as of 20.01)
needs nk/buttons

Creates a button with the label s. If button is pushed, invoke w.

button-set-behavior n --

Controls whether or not the button repeats. n is one of "BUTTON_DEFAULT" or "BUTTON_REPEATER".

button-symbol sym w -- (as of 20.01)
needs nk/buttons

A button with the given symbol (nk:SYMBOL_TRIANGLE_RIGHT etc); invokes w when pressed.

button-symbol-label lbl align sym w -- (as of 20.01)
needs nk/buttons

A symbol button with a label; invokes w when pressed.

chart-add-slot type count min max -- (as of 20.01)

Adds a number slot to the chart.

chart-add-slot-colored type count min max clr1 clr2 -- (as of 20.01)

Adds a number slot to the chart, with normal and active colors.

chart-push n -- n'

Pushes a number to a chart.

chart-push-slot value slot -- (as of 20.01)

Pushes value into a specific chart slot .

checkbox s T -- T

Creates a checkbox with label s and initial state T (true is "checked"). Returns the checked state after processing.

circle -- (as of 23.05)

Draws a filled circle at the current position with radius set by nk:set-radius . If nk:pen-width is not 0, then an outline of that thickness in nk:pen-color is drawn as well.

clicked? btn rect down -- T (as of 20.01)

Returns true if the button was clicked down (true for down, false for up) in the rectangle.

close-this! nk -- (as of 20.01)

Forces the specified screen window to be closed.

close-this? nk -- nk T (as of 20.01)

Returns true if the specified screen window should be closed.

close? -- T (as of 20.01)

Returns true if the current screen window should be closed.

color-chooser rect m -- T (as of 24.04)
needs gui/color

Displays a 'drop down' color chooser, initially filling rect . The initial color is passed in the "color" member of m . If "text" is present that will be drawn in white-on-black in the center of rect , in "font". If "cb" is provided, it is invoked if the color is changed. Usually, color is the name of a var which contains the color, and it gets updated by the actual color-picker.

color-picker v -- (as of 20.01)

Selects a color using an initial color. The color is placed back in the variable, as an array of [R,G,B,A] in the range [0-1].

combo a n high pt -- n' (as of 20.10)

Creates a combo-box whose values in the dropdown are taken from an array of strings. The initial selection is n , and the height of each item in the list is high . The overall (x,y) size is given by pt . It returns the current selection. If pt is a number, then it is the number of rows of items to show.

combo-begin-color clr a -- (as of 20.01)

Starts a combo box with the given color and size a .

combo-begin-label s a -- (as of 20.01)

Start a combo box with the label and size a .

combo-cb m cnt n high pt -- n2 (as of 20.10)

Same as nk:combo , but invokes the cb word (from the map) to get the data to show. That word's SED is m n -- s .

The map m has at least the key "cb" which is the word to invoke to get data. cnt is the count of possible items. If pt is a number, it is the number of rows to show; otherwise, it is a (x,y) size. It may also have a member sep which is a number of pixels the "separator" width is.

combo-end -- (as of 20.01)

Ends a combo box.

contextual-begin flags pt rect -- n (as of 20.10)

Starts a contextual menu with the given flags, of size pt , triggered by right-clicking in the bounds rectangle.

contextual-close -- (as of 20.10)

Closes the contextual menu.

contextual-end -- (as of 20.10)

Ends the contextual menu definition started with nk:contextual-begin .

contextual-item-image-text img s align -- (as of 20.10)

Adds a text item along with an image to the contextual menu, with specific text alignment.

contextual-item-symbol-text sym s align -- (as of 20.10)

Adds a text item with a built-in symbol to the contextual menu, with specific text alignment.

contextual-item-text s align -- (as of 20.10)

Adds a text item to the contextual menu with specific text alignment.

cp! xpos ypos -- (as of 21.03)

Sets the current position (x,y) where the next widget will be placed.

cp@ -- xpos ypos (as of 21.03)

Get the current position (x,y) where the next widget will be placed.

curpos -- pt (as of 23.05)

Gets the current position.

cursor-load img xofs yofs -- X (as of 23.05)

Creates a new cursor from the given image. The "hot spot" of the cursor is at (xofs,yofs) in the image.

cursor-set n -- | X -- (as of 23.05)

Set the cursor. If given is a number, then 0: arrow, 1: I-beam, 2: wait, 3: crosshair, 4: waitarrow, 5: size-nw-se, 6: size-ne-sw, 7: size-we, 8: size-ns, 9: size-all, 10: no, 11: hand. Numbers outside that range are ignored.

It may also be given an item created by nk:cursor-load , which is user-dependent.

cursor-show T -- (as of 23.05)

If true , shows the cursor; otherwise hides it.

display-info -- a (as of 20.02)

Returns information about each connected physical display on the system.

display@ -- n (as of 20.02)

Returns the display index of the current screen-window.

do x -- (as of 20.01)

Passes the item to the GUI (main) task for processing. If it is a:

  • word: it gets invoked
  • string: it gets "eval"ed
  • map: then the word contained in the "cb" key is invoked, with x on TOS

Any other type is ignored.

down? n -- T (as of 20.01)

Returns true if the mouse button is down.

draw-image rect img clr -- (as of 20.01)

Draws the image in the given rectangle, filling as needed with the color.

draw-image-at pt whence img clr -- (as of 20.03)

Draws the image without resizing it, at the point. whence determines what the reference point of the image position is, one of:

  • 0 = top-left
  • 1 = top-right
  • 2 = bottom-left
  • 3 = bottom-right
  • 4 = center
draw-image-centered rect img clr -- (as of 20.03)

Same as nk:draw-image , but centers the image in the rectangle without resizing it.

draw-sub-image rect1 img clr rect' -- (as of 21.01)

Draws the portion of the image given by the rectangle rect2 in the rectangle rect1 , filling as needed with the color.

draw-text rect s font clr1 clr2 -- (as of 20.01)

Draws the text using the font in the rectangle. clr1 is the background color, clr2 is the foreground color.

draw-text-centered rect s font clr1 clr2 -- (as of 22.02)

Same as nk:draw-text , but centers the text in the rectangle (or on it, if the text is wider than the rectangle).

draw-text-high rect s font clr1 clr2 high -- (as of 20.01)

Same as nk:draw-text , but resizes the font to high pixels.

draw-text-wrap rect n s font clr1 clr2 high -- rect' xofs yofs | [rect,n,s,font,clr1,clr2,high,show] -- rect' xofs yofs (as of 21.01)

Like nk:draw-text-high , but wraps the text in the given rectangle. high is the "row height", which if

  • 0: the row height is the font height X 1.2
  • negative: the row height is font height-high
  • positive: row height is that many pixels

Returns the unused portion of rect , and the x-offset (in pixels) where the text drawing ended (on the first 'row' of the returned rect' ).

The input parameter n is the offset from the left of rect to start drawing. This allows you to pass the results of a previous call to start drawing.

The yofs returned is the height of total text output.

Also accepts an array of the parameters; if "show" is present, it determines whether or not the text is actually output.

drivers -- a (as of 21.08)

Returns an array containing the SDL2 video drivers. The first entry is the current driver, or null if no driver is being used.

dropped nk s T -- (as of 21.08)
DEFFERED

Invoked when a file name or text is dropped. The string is the name of the item and true is on TOS if the item is a file.

dropping nk T -- (as of 21.08)
DEFFERED

Invoked when a "drop" event begins or ends, passed true if the drop is beginning, false otherwise.

edit-focus x --

Sets focus (if x is a number of flags) or removes focus (if x is null ) for an edit control.

edit-string s n1 n2 n3 -- s n3 (as of 20.01)

s is the string to edit; n1 is its max size, n2 is flags, n3 is a nk_plugin_filter enum, Returns the edit state, modifies the string

event -- (as of 20.01)

Checks for and processes events. "Events" can be mouse input or motion, keyboard input, OS window messages, etc.


See also: nk:event-msec
event-boost -- (as of 20.06)

Temporarily sets the nk:event-msec value to 1 msec, for 1 second. This is necessary in some scenarios (such as orientation change if msec was -1, in which case it's done automatically) to ensure events gets properly processed.

event-msec n -- (as of 20.01)

Sets the number of milliseconds nk:event will wait for events to occur before timing-out. If 0, events are polled; that is, nk:event returns immediately if no events need to be processed. The default wait is 200 msec.


See also: nk:event nk:event-wait
event-wait n -- (as of 20.02)

Sets the number of milliseconds nk:event sleeps while waiting for nk:event-msec milliseconds to pass before timing-out. If less than zero, it is set to zero.


See also: nk:event nk:event-msec
event? -- n (as of 23.05)

Returns a bitmap of the event(s) which occurred for the current render. Values are some combination of:

value description
0x01 caused by nk:do
0x02 input: mouse or keyboard
0x04 window: resize, focus, etc.
0x08 os: app quit, etc.
0x10 drag-n-drop

See also: nk:event-msec nk:event
fill-arc pt n a clr -- (as of 20.01)

Fills the given arc with a center at pt , a radius of n , and a min and max angle in the array a [startangle, endangle].

fill-circle rect clr -- (as of 20.01)

Fills the circle fitting in the rect with the clr.

fill-color n -- (as of 23.05)

Sets the "pen color" for drawing with line-to, move-to etc.

fill-poly a clr -- (as of 20.01)

Fills in a polygon from an array of points [x,y] which are its vertices.

fill-rect rect n clr -- (as of 20.01)

Fills the rectangle, with corners of a radius n and the given color.

fill-rect-color rect n l t r b -- (as of 20.01)

Fills the rectangle, with the colors [l,t,r,b] for 'left', 'top', 'right', and 'bottom'.

fill-triangle pt1 pt2 pt3 clr -- (as of 20.01)

Fills the triangle defined by the three pts with the clr.

finger m -- (as of 23.06)
DEFFERED

If the system detects a finger motion, this is invoked with m:

key type description
x n normalized x coordinate of the gesture. (0..1)
y n normalized y coordinate of the gesture. (0..1)
dx n normalized x motion (-1..1)
dy n normalized y motion (-1..1)
press n normalized finger pressure (0..1)
kind n 0=up, 1=down, 2=motion

A finger-down event gets translated as well into a left-mouse-down, and finger-up into left-mouse-up.

flags! n -- (as of 21.04)

Sets the Nuklear window flags for the current active widget/window. Use with caution, as it might have unexpected side-effects!


See also: nk:flags@
flags@ -- n (as of 21.03)

Gets the Nuklear window flags for the current active widget/window.


See also: nk:flags!
flash nk n -- (as of 21.08)

Flashes the specified system-window (the current one if 'nk' is null). The parameter 'n' is 0 for "stop flashing", 1 for "flash briefly" and 2 for "flash until focused".

fullscreen T -- (as of 20.04)

If true , make the current system-window "full screen"; otherwise, make it "windowed".

gesture m -- (as of 21.08)
DEFFERED

If the system supports gestures, then if a gesture is input by the user, a map containing information on the gesture is received:

key type description
x n normalized x coordinate of the gesture. (0..1)
y n normalized y coordinate of the gesture. (0..1)
theta n amount the fingers rotated during this gesture
dist n amount the fingers moved during this gesture
fingers n number of fingers in the gesture
get s -- x | a -- x (as of 20.01)

Gets the item x corresponding to the key s in the currently active begin..end block. If passed an array, gets all associated values.

get-row-height -- n (as of 20.02)

Returns the current minimum layout row-height (including padding).

getfont s -- font | null -- font

Returns a font of the given name in the current NK context. null returns the current font.

getmap -- m

Returns a map of the current window's backing store.

getmap! nk -- nk m (as of 21.09)

Returns the entire map of the specified window's backing store.

gl? -- m (as of 20.02)

Returns either null or a map containing information about the GL subsystem.

grid row #rows col #cols -- rect | a -- rect (as of 21.07)

Gets the rectangle corresponding to the given (row,col), for as many #rows high and #cols wide. A negative row or col means take that row or col from the end of the grid; that is, row -1 corresponds to the last row of the grid.

Note that the values given are not checked, so if you want valid rectangles you need to make sure the (row,col) is less than the (rows,cols) given to nk:layout-grid-begin .

grid-peek -- rect (as of 24.04)

Returns the current grid passed to nk:grid-push .

grid-push rect -- (as of 21.07)

Like nk:layout-space-push but for grids. Use this to position any widget within a grid. The rectangle given does not necessarily have to have come from nk:grid , but why would you do that?

group-scroll-ofs s -- xofs yofs (as of 21.03)

Gets the scroll offset of the named group.

group-scroll-ofs! s xofs yofs -- (as of 21.03)

Sets the scroll offset of the named group.

hovered? rect -- T (as of 20.01)

Returns true if the mouse is over the rectangle.

hrule clr T -- (as of 23.08)

Creates a "horizontal rule" filling the current space, in the given color. If TOS is true and there's enough space, does rounded ends.

image img -- (as of 20.01)

Draws the image in the layout area.

init -- n (as of 20.01)

Initializes the NK (e.g. GUI) subsystem; returns 0 on failure, otherwise 1.

input-button id xofs yofs T --

Presses the mouse button id at position (xofs,yofs). If T is *true, button is 'down'.

input-key n T --

Inputs a key as if it were typed. n is one of the KEY_* enums, and T is true if the key is down, false if up.

input-motion xofs yofs --

Moves the mouse to position (xofs,yofs).

input-scroll pt --

Scrolls to the given position.

input-string s --

Inputs the string as if it were typed.

key-down? n -- T (as of 20.01)

Returns true if the key is being pressed.

key-pressed? n -- T (as of 20.01)

Returns true if the key is currently pressed.

key-released? n -- T (as of 20.01)

Returns true if the key is currently released.

knob min max step n dir dead T -- n' (as of 24.06)

Draws a "knob control". If T is true , n is a float; otherwise an int.

label s flags -- (as of 20.01)

Draws a label using the given flags .

label-colored s flags clr --

Same as nk:label but making the text colored.

label-wrap s --

Same as nk:label , but wrapping the text within the bounds of the widget.

label-wrap-colored s clr --

Same as nk:label-wrap , but with the given color.

layout-bounds -- rect (as of 20.01)

Returns the bounds rectangle allocated after nk:layout-space-begin

layout-grid-begin rect rows cols -- | rect m -- (as of 21.07)

Begins a "grid layout", with as many evenly-spaced rows and columns as indicated. If "rect" is null , uses the entire available space in the window; otherwise, uses the rectangle. If a map is given instead, the following keys may be used:

key type description
cgap n If present, the number of pixels to leave between each column
cols n,a If a single number, split evenly into that many columns; if an array, see below
rgap n If present, the number of pixels to leave between each row
rows n,a If a single number, split evenly into that many rows; if an array, see below
margin n,a If a single number, margin in pixels ; if an array, [left,top,right,bottom] margins

Arrays of numbers for 'rows' and 'cols': the length of the array determines the number of rows or columns. If the number is greater than 1, it means the item should be that many pixels wide (or high). If it is between 0 and 1, it means it should be that percentage of the space. If it is negative, it means it should take up the rest of the available space (after the other items have been allocated).

Note that grids may be nested, so that you may use the result of nk:grid as input to nk:layout-grid-begin , to create arbitrarily complex layouts.

The "margin" is taken around the enclosing rectangle, not around each grid item.

layout-grid-end -- (as of 21.07)

Terminates the current grid layout.

layout-push-dynamic -- (as of 20.01)

Adds a column to a templated row that dynamically grows and can go to zero if not enough space.

layout-push-static n -- (as of 20.01)

Adds a static column that does not grow and will always have the same size.

layout-push-variable n -- (as of 20.01)

Adds a column that dynamically grows but does not shrink below specified pixel width.

layout-ratio-from-pixel n -- n' (as of 20.01)

Utility function to calculate window percentage from a width in pixels.

layout-reset-row-height -- (as of 20.01)

Resets the currently used minimum row height to the font height.

layout-row fmt h [ratio] --

Starts layout rows where the column widths are determined by an array. There are as many columns as elements in the array, and the width is determined to be a number of pixels, if it's ≥ 1, or a percentage of the window width otherwise.

layout-row-begin fmt high cols --

Begin layout of rows using nk:layout-push , until nk:layout-row-end . fmt is one of DYNAMIC or STATIC.

layout-row-dynamic hi n -- (as of 20.01)

Sets current row layout to share horizontal space evenly between n columns of widgets. Once invoked, all subsequent widget calls beyond n will allocate a new row with same layout. The height hi may be 0 to allow auto-layout.

layout-row-end -- (as of 20.01)

Finishes previously started row.

layout-row-height n -- (as of 20.01)

Sets the currently used minimum row height.

layout-row-push n --

Pushes the ratio or width n

layout-row-static hi wide n -- (as of 20.01)

Sets the current row layout to fill n widgets in a row with the same horizontal size wide . Once invoked, all subsequent widget calls beyond n will allocate a new row with same layout. The height hi may be 0 to allow auto-layout.

layout-row-template-begin n -- (as of 20.01)

Begins the row template declaration with a row-height of n .

layout-row-template-end -- (as of 20.01)

Marks the end of the row template.

layout-space-begin fmt hi n -- (as of 20.01)

Begins a new layout space that allows specifying each widget's position and size. fmt is DYNAMIC for window ratio, or STATIC for fixed size columns. hi is height of each widget in row, or 0 for auto layout. n is the count of widgets in the row, e.g. number of columns.

layout-space-end -- (as of 20.01)

Marks the end of the layout space.

layout-space-push a -- (as of 20.01)

Pushes the position and size of the next widget in own coordinate space either as pixel or ratio. a is position and size in layout space local coordinates

layout-widget-bounds -- rect (as of 20.01)

Calculates the bounds a static layout row can fit inside the current window.

line-rel pt -- (as of 23.05)

Draws a line to the pt relative to the current position.


See also: nk:line-to
line-to pt -- (as of 23.05)

Draws a line from the "current position" set with nk:move-to , to pt , using the pen width set with nk:pen-width and the stroke color set with nk:pen-color . Afterwards, the current position is pt .

list-begin id flgs high total b -- (as of 20.03)

Starts a list.


See also: nk:list-end nk:list-new
list-end b -- (as of 20.03)

Ends a list.


See also: nk:list-begin nk:list-new
list-new -- b (as of 20.03)

Allocates a buffer big enough to serve as a 'nk_list_view'


See also: nk:list-begin nk:list-end
list-ofs s n -- (as of 24.04)
needs nk/loaded

Sets the scrollbar offset n in the list titled s .

list-range b -- begin end count (as of 20.03)

Returns the numbers for the given list's current begin, end, and count.


See also: nk:list-begin nk:list-end
m! s x -- (as of 20.01)

Puts the item x in the nk's backing store under the key s .

m@ s -- x | a -- x (as of 20.01)

Gets the item corresponding to the key in the nk's backing store. If passed an array, gets all associated values.

make-style m -- X (as of 20.01)

Creates a new item containing style information from the map. Use it with nk:use-style . See the manual for details on the map keys and values.


See also: nk:use-style
max-vertex-element n1 n2 -- (as of 20.01)

Sets the maximum number of "elements" n1 and "vertices" n2 per render frame. The defaults are 512K and 128K respectively. Limited by the amount of memory in your video card.

maximize T -- (as of 23.09)

Maximizes the screen window if true , or restores it.

measure s -- pt (as of 20.01)

Returns a pt containing the height and width the string would take in the current font.

measure-font s font -- pt | s s' -- pt (as of 20.01)

Returns a pt containing the height and width the string would take with the font (either a string naming a defined font, or a font*).

menu-begin s align pt -- T | s align pt img -- T | s align pt sym -- T

Begins a menu with a given size pt , text-alignment, and label. May also have an image or symbol. In the latter two cases, if null is used instead of a string, no text will be shown.

menu-close --

Closes an open menu.

menu-end --

Ends a menu definition.

menu-item-image s flg img w --

Begins a menu item with an image and label, with a given alignment. Invokes w if the menu was selected.

menu-item-label s flg w --

Begins a menu item with a label, with a given alignment. Invokes w if the menu was selected

menu-item-symbol s flg sym w --

Begins a menu item with a symbol and label, with a given alignment. Invokes w if the menu was selected.

menubar-begin --

Starts menu layout.

menubar-end --

Ends menu layout.

minimize T -- (as of 23.09)

Minimizes the screen window if true , or restores it.

mouse-pos -- xpos ypos (as of 20.03)

Returns the (x,y) position of the mouse in the currently focused screen window.

move-back pt -- (as of 23.05)

Moves the "current position" to the previously set one.

move-rel pt -- (as of 23.05)

Moves the "current position" to a new position relative to the current one.


See also: nk:line-to
move-to pt -- (as of 23.05)

Moves the "current position" for drawing to the point [x,y] .


See also: nk:line-to
msg title msg -- (as of 23.07)

Prints a simple message box (usually for errors).

msgdlg opts -- (as of 20.01)
needs nk/msgdlg

Display a message dialog with parameters from the map opts. Keys:

  • "title" - the title of the dialog
  • "msg" - the contents of the dialog
  • "buttons" - an array of maps containing:
  • "label" - the text of the button
  • "cb" - the word to call back when the button is pressed
  • "bounds" - a rectangle in which to locate the message; if 'null', the current window is used
  • "font" - the font to use for the message (default to window font)
  • "clr" - the color to use for the message (defaults to black)
  • "bfont" - the font to use for the buttons (default to window font)
ontop nk T -- (as of 22.08)

Makes that system window 'topmost' and keeps it above the rest (if true ; otherwise not)

option s T -- T

Creates an option (radio-button) with the label s and initial state T (true is "checked"). Returns the checked state after processing.

pen-color n -- (as of 23.05)

Sets the "pen color" for stroke-drawing with line-to, move-to etc.

pen-width n -- (as of 23.05)

Sets the "pen width" for drawing with line-to, move-to etc.

plot type a -- (as of 20.01)

Plots an array of numbers with the type of chart (CHART_LINES, CHART_COLUMN).

plot-fn x type w count offset -- (as of 20.01)

Plots an array of numbers with the type of chart (CHART_LINES, CHART_COLUMN), invoking w with a SED of x n -- n' for each of count items starting at the given offset.

polygon a -- (as of 24.02)

Draws a filled polygon using the current position as one vertex, and the array of other vertices as relative positions. Uses the current fill color and if a pen width is given, an outline stroke. Current position remains the starting vertex.

pop-font -- (as of 20.01)

Pops the font which was set with nk:push-font . The previous font becomes current.


See also: nk:push-font
popup-begin kind title flag size -- n

Starts a popup definition.

popup-close -- (as of 20.10)

Closes the popup.

popup-end --

Ends a popup definition.

popup-scroll-ofs -- xofs yofs (as of 20.10)

Returnss the current scroll offsets of the popup.

popup-scroll-ofs! xofs yofs -- (as of 20.10)

Sets the scroll offsets of the current popup.

progress max T v --

Creates a progress bar from [0..max ]. If T is true, the user can modify the bar. v is a var, a string, or a number as with nk:slider


See also: nk:slider
prop-int min max step v -- (as of 20.01)
needs nk/property

Creates a slider which modifies the

pt-in? rect pt -- T (as of 22.02)

Returns true if the point is within the rectangle (inclusive of rectangle boundaries).

pt>local pt -- pt' (as of 20.01)

Converts the point from screen coordinates to local ones.

pt>screen pt -- pt' (as of 20.01)

Converts the point from local coordinates to screen ones.

push-font s -- (as of 20.01)

Uses the named font (as defined in the fonts atlas). Paired with nk:pop-font .


See also: nk:pop-font
raise nk -- (as of 22.08)

Raises that system window above others, and gives it focus.

rect-rel pt -- (as of 23.05)

Strokes and fills a rectangle relative to the current position.

rect-to pt -- (as of 23.05)

Strokes and fills a rectangle from the current position to pt .

rect>local rect -- rect' (as of 20.01)

Converts the rectangle from screen coordinates to local ones.

rect>screen rect -- rect' (as of 20.01)

Converts the rectangle from local coordinates to screen ones.

released? n -- T (as of 20.01)

Returns true if the mouse button was pressed and is now released.

render -- (as of 20.01)

Invokes the Nuklear GL rendering routine, which iterates the list of items "drawn" and causes them to be output to the screen. In most systems, the output will be to the hardware-accelerated renderer (via GL or Metal etc.). On some systems, a much slower software renderer will be used because the hardware doesn't support accelerated rendering. It is invoked by the default nk:render-loop .


See also: nk:render-loop nk:frame
render-timed w n -- (as of 23.05)
needs nk/render-timed

A render-loop which creates a separate task for timing the loop. Within the render loop, invoke nk:timer? to see if the render was caused by a timer-timout (or if false , some other event). n is the number of milliseconds the timer delays.

rendering --
DEFFERED
needs nk/loaded

Invoked when the rendering loop is first started.

restore -- (as of 21.06)

Restores the previously saved GL transformation matrix.

rotate angle x y z -- (as of 21.06)

Rotates the GL canvas through the given angle around the vector (x,y,z)

rotate-rel angle -- (as of 23.05)

Rotates the canvas by angle degrees clockwise around the current position.

rtl! T -- (as of 24.03)

Sets the "RTL" (right-to-left) value for the current NK window. This inverts the meaning of "left" and "right" so that you needn't have code to switch between LEFT and RIGHT alignment if you print RTL language text (Hebrew/Arabic/Farsi etc). The default is to output LTR (e.g. false for RTL).

rtl? -- T (as of 24.04)

Gets the "RTL" (right-to-left) value for the current NK window. Useful in widgets/libraries to determine proper RTL orientation.

save -- (as of 21.06)

Saves the GL transformation matrix.

scale x y z -- (as of 21.06)

Scales the GL canvas by the given amounts along the (x,y,z) axes.

scancode? n -- T | a -- a' (as of 20.03)

Returns true if the key indicated by the SDL scan-code number n is pressed. needs nk/keyboard to load enums for the scan-codes. If an array of scan-codes is given, an corresponding array is returned.

screen-saver T -- (as of 21.02)

Enables the screen-saver (if true ) or disables it.

screen-size -- a (as of 20.01)

Returns the screen's size [w,h] in pixels.

screen-win-close nk -- (as of 20.01)

Lets the given screen window know that it should close.

selectable str align img val -- val | str align n val -- val | str align null val -- val (as of 20.01)

Creates a "selectable" with a label given by str , aligned according to align , with a value (true/false/1/0) of val . Returns the possibly modified val . The item under val may be an image, a number (of a nk symbol), or null .

set s x -- (as of 20.01)

Puts the item x in the currently active window's backing store under the string key s .

set-font s -- (as of 21.01)

Uses the font with the given name. Unlike nk:push-font , simply sets the font rather than pushing it on the font stack.


See also: nk:push-font
set-num-vertices n1 n2 n3 -- (as of 20.01)

Sets the number of vertices used to draw a circle n3 , a curve n2 and an arc n1 . The defaults are 21; setting to higher values makes smoother curves, with a performance and memory cost. Avoid setting to a number which makes each segment drawn less than a pixel -- that's just a waste of resources.

set-radius n -- (as of 23.05)

Sets the radius of a subsequent nk:circle .

setpos pt --

Sets the position of NK window.

setwin s -- T (as of 20.01)

Sets the current screen window to the named one. Returns true if successful; false if the name doesn't correspond to an active or known window.


See also: nk:win nk:win?
show nk T -- (as of 21.09)

Shows (if true ) or hides the screen-window. If null means "current screen-window".

slider min max step val T --

Creates a slider control. If T is true , it's for integer values; otherwise, float values. The item val is either a var, in which case its value is modified by the slider, or a string in which case the value accessed by get/put is modified.


See also: nk:progress
slider-int min max step v -- (as of 20.01)
needs nk/sliders

Creates a slider which modifies the

space -- (as of 21.02)

Takes the place of the item which was supposed to have been inserted in a row, allowing the item to appear or not, without changing the layout. That is, allows you to omit an item from a layout.

spacing n -- (as of 20.01)

Sets the number of columns in this layout.

stroke-arc pp1 n1 a n2 clr -- (as of 20.01)

Strokes an arc of thickness n2 centered on the point pt1 , with radius n1 , color clr , with starting and stopping angles from a .

stroke-circle rect n clr -- (as of 20.01)

Strokes a circle fitting the rectangle, with line thickness n , in the given color.

stroke-curve pt1 pt2 pt3 pt4 n clr -- (as of 20.01)

Strokes a cubic-Bézier curve from point p1 to end point p4 , with control points p2 and p3 , and thickness n in the given color.

stroke-line pt1 pt2 n clr -- (as of 20.01)

Strokes a line of thickness n using the color, from point pt1 to point p2 .

stroke-polygon a n clr -- (as of 20.01)

Stroke an array of points as a polygon, with line thickness n , in the given color.

stroke-polyline a n clr -- (as of 20.01)

Strokes an array of points, with line thickness n , in the given color.

stroke-rect rect n1 n2 clr -- (as of 20.01)

Strokes a rectangle with corners of radius n1 and line thickness n2 , in the given color.

stroke-tri pt1 pt2 pt3 n clr -- (as of 20.01)

Strokes a triangle between the given points, with line thickness n , in the given color.

style-from-table a -- | null -- (as of 20.01)

If given an array of numbers with nk:COLOR_COUNT values, uses them to set the colors in this "style". If given null , resets to the default.

swipe m -- (as of 23.06)
DEFFERED

If a finger-swipe motion occurs, this is invoked with m:

key type description
x n normalized x coordinate of the gesture. (0..1)
y n normalized y coordinate of the gesture. (0..1)
t n angle (radians) of swipe
d n direction of swipe: 0=indeterminate ; 1= left, 2=right, 3=up, 4=down
swipe-dir-threshold n -- (as of 23.06)

Sets the threshold below which the difference between x and y values makes it impossible to choose a "direction" of swipe. The default is 0.1.

swipe-threshold n -- (as of 23.06)

Sets the threshold below which a finger motion will not be considered a swipe event. The default is 0.02.

text s -- (as of 23.05)

Outputs the text using the text-font , in color pen-color , aligned text-align , relative to the current position.

text-align n -- (as of 23.05)

Sets the text alignment for nk:text .

text-font s -- (as of 23.05)

Sets the font for drawing.

text-pad rect -- (as of 23.05)

Sets the padding [left,top,right,bottom] for the text output. That is, the output rectangle is increased by the given size.

text? -- s (as of 20.01)

Returns any text which has been entered (key-presses). If there's no input, an empty string is returned.

timer-delay n -- (as of 23.05)
needs nk/render-timed

Set / change the number of milliseconds the timer-task delays, and notify the timer task of the change.

timer? -- T (as of 23.05)
needs nk/render-timed

Returns true if the current event causing the render is a user-event

toast s n -- (as of 24.05)
needs nk/toast

Displays the given text in a notice at the bottom of the screen for n seconds.

tooltip s -- (as of 20.10)

Presents a tooltip.

translate x y z -- (as of 21.06)

Translates the GL canvas by the given amounts along the (x,y,z) axes.

tree-pop --

Pops the most recent tree state; only invoke if nk:tree-state or nk:tree-state-push returns true .

tree-state-push kind img s state -- newstate | kind s state -- newstate

Pushes a new tree node. state is either MAXIMIZED or MINIMIZED. It returns the new state after the call. Prefer: nk:tree-push as it manages state on its own.


See also: nk:tree-pop nk:tree-push
triangle pt pt -- (as of 24.02)

Draws a filled triangle using the current position as one vertex, and the other two (relative) points as the other vertices. Uses the current fill color and if a pen width is given, an outline stroke. Current position remains the starting vertex.

use-style X -- | m -- (as of 20.01)

Uses the style created by nk:make-style , or an equivalent map. If X is null , pops the style (reverts to previous style).


See also: nk:make-style
vsync T --

If false , doesn't wait for 'vertical sync' to swap GL buffers. Defaults to true , meaning buffers swap at your monitor's vertical sync rate.

widget -- rect n (as of 20.01)

Creates space for a new widget in the current layout. Returns the allocated bounds rect , and the status n which is one of WIDGET_INVALID, WIDGET_VALID, or WIDGET_ROM.

widget-bounds -- a (as of 20.01)

Returns the bounds [x,y,w,h] of the current widget.

widget-disable T -- (as of 23.09)

If true , begins a "disabled widgets" section until false nk:widget-disable . Widgets in the disabled area will be shown differently and are incapable of interaction.

widget-fitting pt -- rect n (as of 20.01)

Same as nk:widget but with [x,y] padding given by pt

widget-high -- n (as of 20.01)
needs nk/widgets

Returns the height of the current widget.

widget-hovered? -- T (as of 20.01)

Returns true if the mouse is over the current widget.

widget-mouse-click-down? n T -- T (as of 20.01)

Returns true if the specified mouse button is down (true ) or up (false ) in the current widget.

widget-mouse-clicked? n -- T (as of 20.01)

Returns true if the specified mouse button was clicked in the current widget.

widget-pos -- pt (as of 20.01)
needs nk/widgets

Returns the local position [x,y] of the current widget.

widget-size -- pt (as of 23.09)

Returns the size allocated for the current widget.

widget-size-allot -- pt (as of 20.01)
needs nk/widgets

Returns the size [w,h] of the current widget.

widget-wide -- n (as of 20.01)
needs nk/widgets

Returns the width of the current widget.

win m -- (as of 20.01)

Creates a screen window from the map. A "screen window" is an OS-specific window, an outermost container for nk windows and widgets. The created window will become the "current" window. To use other windows you must make them current using nk:setwin . Throws on failure to create the window. Keys are:

key type description default
alpha n Opacity of the window, in range [0,1.0] 1.0
bg clr Background color to paint the window between frames 0xFF808080
decorated T Does the window have a title bar etc. true
display n The physical display to use 0
font s Default font for items drawn system
fontheight n Default height of font 13
fonts m Map of (id,filename) of all fonts this window or its children will use [system]
fullscreen T If true, make window fill the screen false (true on mobile)
high n Height of the window in pixels screen
maxh n Maximum height, in pixels screen
maximize T Create the window maximized false
maxw n Maximum width, in pixels screen
minh n Minimum height, in pixels 0
minimize T Create the window minimized false
minw n Minimum width, in pixels 0
name s REQUIRED: The name by which this window is known to 8th
onclose w When window clicked 'close', SED nk -- T (return true to close)
onenter w When window entered (true ) or left, SED nk T --
onfocus w When window got (true ) or lost focus, SED nk T --
onminmax w When window maximized (1), restored (0), or minimized (-1) SED nk n --
onmove w When window moved, SED nk x y --
onshow w When window shown (true ) or hidden, SED nk T --
onsize w When window resized, SED nk w h --
resizable T Does the window have a resize widget true
title s The titlebar title appname
topmost T Is the window ‘always on top’ false
unicode-ranges a Ranges of Unicode glyphs to include [low,high],... [0x0020, 0x00FF]
visible T Is the window visible initially true
wide n Width of the window in pixels screen
x n Position of left in pixels centered
y n Position of top in pixels centered

The x, y, wide, and high values are in pixels, unless they are in the range (0,1]. In that case they represent a fraction of the screen size.

The 'fonts' map keys are meaningful identifiers, like "buttonfont", while the values are font descriptor strings (the full path to the TTF file, with an optional colon and pixel size), or a buffer containing a font (e.g. from an asset). An exception will be thrown if no valid fonts were given.


See also: nk:win? nk:setwin nk:close?
win-bounds -- rect (as of 20.01)

Returns the bounds [x,y,w,h] of the currently processed window. Use only within begin... end.

win-bounds! n a -- (as of 20.01)

Sets the position and size of the named window. Changing the bounds of the window currently being processed is not permitted.

win-close s -- (as of 20.01)

Closes the named window. Does not work on the currently active window.

win-closed? s -- T (as of 20.01)

Return true if the named window was closed.

win-collapse s n -- (as of 20.01)

Collapses the named window. Does not work on the currently active window. n is one of MINIMIZED or MAXIMIZED.

win-collapsed? s -- T (as of 20.01)

Return true if the named window is minimized/collapsed.

win-content-bounds -- rect (as of 20.01)

Returns the bounds [x,y,w,h] of the currently processed window's currently visible and non-cliped

win-focus s -- (as of 20.01)

Makes the named window the active one.

win-focused? -- T (as of 20.01)

Return true if the window currently being processed has the focus.

win-hidden? s -- T (as of 20.01)

Return true if the named window was hidden.

win-high -- n (as of 20.01)
needs nk/win

Returns the height of the currently processed window.

win-hovered? -- T (as of 20.01)

Return true if the window currently being processed is being hovered over by the mouse.

win-icon! img -- (as of 24.05)

Sets the icon of the current screen-window.

win-pos -- pt (as of 20.01)
needs nk/win

Returns the screen position [x,y] of the currently processed window.

win-scroll-ofs -- xofs yofs (as of 20.01)

Returns the x,y offsets which are the currently processed window's scrollbar offsets

win-scroll-ofs! xofs yofs -- (as of 20.01)

Sets the currently processed window's scrollbar offsets.

win-show s n -- (as of 20.01)

Shows the named window. n is one of HIDDEN or SHOWN

win-size -- pt (as of 20.01)
needs nk/win

Returns the width and height [w,h] of the currently processed window.

win-title! s -- (as of 24.05)

Sets the title-bar title of the current screen-window.

win-wide -- n (as of 20.01)
needs nk/win

Returns the width of the currently processed window.

win? -- nk (as of 20.01)

Returns the current screen window (or null if there is none).


See also: nk:win nk:setwin nk:close?

Number

Namespace: n
Description: Numbers: integers or floating-point

word sed/description
! n -- n!
needs math/factorial

Returns the factorial of the number n, non-recursively.

* n n2 -- n'

Multiplies the numbers.


See also: n:/ n:+ n:- n:*/
*/ n x y -- n'

Calculates n * (x/y) . Can be faster or more accurate than n x y / * .


See also: n:* n:/
+ n n2 -- n'

Adds two numbers.


See also: n:- n:1+ n:* n:/
+! n v --

Adds the number n to the number held in the variable v . The variable should be invoked by name, and not accessed using @ .

- n n2 -- n'

Subtracts n2 from n .


See also: n:+ n:* n:/ n:1-
/ n n2 -- n'

Divides n by n2 .


See also: n:* n:+ n:- n:*/ n:/mod n:mod
/mod n n2 -- rem quo

Divides n by n2 , returning the integer remainder rem and quotient quo . The returned values satisfy the relation n = (quo*n2) + rem for all numeric types, and rem is always positive. This means that the value quo may not be the same as you would get with n n2 / .

The reason for this is that we want mod to always return a positive value, so that e.g. array offset calculations are correct.

If one of the arguments is not an 'int', then while the relation holds, the remainder could be negative.


See also: n:mod n:/
1+ n -- n'

Increments the number by 1.


See also: n:1- n:+
1- n -- n'

Decrements the number by 1.


See also: n:1+ n:-
< n n2 -- T

Compares two numbers, returning true if n < n2 , otherwise false . To compare ≤ (less or equal) use n:> not .


See also: n:= n:> n:cmp n:sgn n:~=
= n n2 -- T

Compares two numbers, returning true if they are equal, otherwise false .


See also: n:cmp n: n: n:sgn n:~=
> n n2 -- T

Compares two numbers, returning true if n > n2 , otherwise false . To compare ≥ (greater or equal) use n:< not .


See also: n:= n:< n:cmp n:sgn n:~=
>bool n -- T (as of 22.06)

Converts a number (or anything, actually) to explicitly true or false .

BIGE -- e
needs math/big

Returns the number "e" (2.7182...) as a big-float with 130 digits precision.

BIGPI -- pi
needs math/big

Returns the number "pi" (3.1415...) as a big-float with 130 digits precision.

E -- n

The mathematical constant "e" (2.71828...) as a "float". If you want an extended "bfloat", accurate to 130 decimal places, use needs math/big .


See also: n:PI n:BIGE
PI -- n

The mathematical constant "pi" (π = 3.14159...) as a "float". If you want an extended "bfloat", accurate to 130 decimal places, use needs math/big .


See also: n:E n:BIGPI
^ n n2 -- n'

Raises n to the power n2 .


See also: n:* n:exp
_mod x y -- n (as of 21.06)
needs math/fmod

"floored modulo", like the C "fmod()" function, but result has same sign as divisor.

abs n -- n'

Returns the absolute-value of n .

acos n -- n'

Calculates the arc-cosine of the number n , in radians.


See also: n:cos
acosd cos(n) -- n
needs math/trigd

Returns the angle n in degrees, whose cosine is given.

acosh n -- n' (as of 24.03)

Returns the hyperbolic arc-cosine of the input number.

andor n1 n2 n3 -- n4

n4 is the result of n1 n2 band n3 bor

asin n -- n'

Calculates the arc-sine of the number n , in radians.


See also: n:sin
asind sin(n) -- n
needs math/trigd

Returns the angle n in degrees, whose sin is given.

asinh n -- n' (as of 24.03)

Returns the hyperbolic arc-sine of the input number.

atan n -- n'

Calculates the principle value of the arc-tangent of n , in radians in the range [-π/2,+π/2].


See also: n:atan2 n:tan
atan2 x y -- n

Calculates the principle value of the arc-tangent of y/x, in radians.


See also: n:atan n:tan
atand tan(n) -- n
needs math/trigd

Returns the principle angle n in degrees, whose tangent is given.

atanh n -- n' (as of 24.03)

Returns the hyperbolic arc-tangent of the input number.

band n n2 -- n'

Returns the bitwise AND of two numbers.


See also: n:bor n:bxor
between n low hi -- T

Returns true if the number is between low and hi , inclusive; e.g. if low ≤ n ≤ hi .

bfloat n -- n'

Converts the number to a big floating-point representation, if possible.


See also: n:int n:bint n:float
bic n ix -- n' (as of 18.06)

Clears the bits in the number which are set in the bitmap number ix .

bint n -- n'

Converts the number to a big integer representation, if possible. Floating-point n are truncated to integers first.


See also: n:int n:float n:bfloat
binv n -- n' (as of 18.06)

Inverts all bits of the number.

bnot n -- n'

Returns the bitwise NOT of the number n .

bor n n2 -- n'

Returns the bitwise OR of two numbers.


See also: n:band n:bxor
bxor n n2 -- n'

Returns the bitwise XOR of two numbers.


See also: n:band n:bor
cast n bits T -- n2 (as of 20.02)

Ensures that the number is (in binary form) an integer of bits width. So for example, 8 true n:cast would ensure the was "cast" to a "int8_t". That is, 0xFF 8 true n:cast . prints "-127" instead of "255". n is converted first to an "int", and bits must be 64 or less. The lowest bits bits of the integer are then returned, signed if T is true .

ceil n -- n'

Returns the nearest integer, ≥ n .


See also: n:floor n:round n:ceil
clamp n low hi -- n'

Ensure that the number n is not less than low and not higher than hi (e.g. lownhi ). So for example 23 10 20 n:clamp returns "20".


See also: n:min n:max
cmp n n2 -- n'

Compares the two numbers, returning -1 if n < n2 , 0 if equal, and 1 if n > n2 .


See also: n:= n:sgn
comb p k -- comb(p,k)
needs math/comb-perm

Returns the unique combination of p items taken k at a time.

cos n -- n'

Calculates the cosine of n (radians).


See also: n:sin n:tan n:acos
cosd n -- cos(n)
needs math/trigd

Returns the cosine of the angle n, specified in degrees.

cosh n -- n' (as of 24.03)

Returns the hyperbolic cosine of the input number.

emod x y -- n (as of 21.06)
needs math/fmod

"Euclidian modulo", result is always positive

erf n -- n' (as of 24.03)

Returns the "error function" of the input.

erfc n -- n' (as of 24.03)

Returns the "complementary error function" of the input, equivalent to 1 swap n:erf n:- .

exp n -- n'

Exponential of n : raises "e" to the n power; inverse of n:ln .


See also: n:ln
expm1 n -- n' (as of 19.09)

Returns expm1(n), e.g.: e^n-1

expmod n n2 n3 -- n' (as of 17.05)

Calculates the value of n raised to the n2 power, modulo n3 . Works for integer and big integer values only, otherwise returns null . Also returns null on overflow or other errors.

Note: n2 must be positive and less than n3 .

float n -- n'

Converts the number to a (native IEEE double) floating-point representation, if possible.


See also: n:int n:bint n:bfloat
floor n -- n'

Returns the nearest integer, ≤ n .


See also: n:trunc n:round n:ceil
fmod n n2 -- n' (as of 21.06)

Remainder of n divided by n2 . Unlike n:mod , it keeps the floating-point remainder. That is, 5.25 5 fmod gives 0.25 rather than 0 . The sign of the result is the same as that of the dividend, e.g. -3 2 fmod gives -1 .

frac n -- n'

Returns the fractional part of the number n . That is, 1.234 n:frac returns 0.234 .

gcd n n2 -- n' (as of 17.05)

Calculates the greatest-common-divisor of the two numbers. Returns null if NaN or Inf etc are given.

int n -- n'

Converts the number to a (native 64-bit) integer representation, if possible. This is equivalent to casting to an "int" in C-like languages.

If the conversion is not possible (because it is outside the range of an integer), the original number is returned.


See also: n:bint n:float n:bfloat
invmod n n2 -- n' (as of 17.05)

Calculates the value of the inverse of n , modulo n2 . Works for integer and big integer values only, otherwise returns null . Also returns null on overflow or other errors.

kind? n -- n n'

Returns a number corresponding to the given number's "kind":

  • 0: native integer
  • 1: native floating point
  • 2: big integer
  • 3: big floating point
  • 4: NaN
  • 5: Inf
  • 6: NegInf

If m is negative, it indicates that n is a complex number of the given type (e.g. -2 means "a complex number whose components are big integers").

lcm n n2 -- n' (as of 17.05)

Calculates the least-common-multiple of the tow numbers. Returns null if NaN or Inf etc are given.

lerp lo hi t -- n (as of 23.06)

Linear interpolation between lo and hi based on the parameter t which should be in the range [0,1]. Converts inputs to regular floats; use the math/interpolate library if you need big floats or big ints.


See also: n:lnerp
ln n -- n'

Natural logarithm (log base "e") of n .


See also: n:exp
ln1p n -- n' (as of 19.09)

Returns ln(n+1)

lnerp lo hi t -- n (as of 23.06)

Logarithm interpolation between lo and hi based on the parameter t which should be in the range [0,1]. The range is positive non-zero numbers. Converts inputs to regular floats; use the math/interpolate library if you need big floats or big ints.


See also: n:lerp
logistic n -- n' (as of 24.03)
needs math/sigmoid

Returns the "logistic" sigmoid value of the input number, normalizing it to the range 0..1. The returned value is a 'float' though intermediate values may be promoted to 'bfloat' for accuracy reasons.

max n n2 -- n'

Returns the larger of two numbers.


See also: n:min
median a -- a n
needs math/median

Calculate the median (middle) value of an array of numberS.

min n n2 -- n'

Returns the smaller of two numbers.


See also: n:max
mod n n2 -- n'

Divides n by n2 , returning the integer remainder, which is always positive (even if the divisor is negative).


See also: n:/mod n:/
neg n -- n'

Negate the number n : change its sign from positive to negative and vice-versa.

odd? n -- n' (as of 18.06)

Returns 0 if the number is even, 1 if it is odd.

perm p k -- perm(p,k)
needs math/comb-perm

Returns the permutation of p items taken k at a time.

prime? n -- n T (as of 17.05)

Determines probabilistically whether or not the number n is prime. If n is not a "big integer", returns null .

quantize val quantum -- qval
DEFFERED
needs math/quantize

Accept a number val and a number quantum, which is the boundary to which you wish to quantize. Returns qval, which is the quantized number. See also: n:quantize!.

quantize! n --
needs math/quantize

Sets the kind of quantization to do. A value of n of 0=none, 1=up, 2=down, 3=nearest.

r+ n -- (as of 18.05)

Add the number to the number on the r-stack.

range low high -- arr
needs math/range

Returns an array of integer numbers in the range [low,high]. So 1 3 n:range returns [1,2,3]. Handles incorrect low vs. high by rearranging the values so the lower is first.

rot32l n1 cnt -- n2
needs math/rot

Rotate the number n1 as a 32-bit integer, cnt times left. Bits passed "off the end" are replaced on the right.

rot32r n1 cnt -- n2
needs math/rot

Rotate the number n1 as a 32-bit integer, cnt times right. Bits passed "off the end" are replaced on the left.

round n -- n'

Round to the nearest integer. By default, if the fractional part is 0.5 or greater, rounds up (down, if n is negative).

Rounding algorithm can be controlled using n:rounding .


See also: n:rounding n:trunc n:floor n:ceil
round2 n n2 -- n (as of 16.08)

Rounds the number according to n2 . If it is:

  • 0: then this is exactly the same as n:round
  • 0: then n is rounded to that many digits to the right of the decimal

  • <0: then that many significant digits is kept

So 123.456 2 round2 returns 123.460 , while 123.456 -2 round2 returns 120.000 .


See also: n:round
rounding s -- (as of 19.09)

Takes a string of "NEAREST", "ZERO", "INF", or "NEGINF" and sets the rounding method used for floating-point operations.


See also: n:round
running-variance a n -- a
needs math/mean

Calculates mean and variance of a "stream" of numbers. TOS is an array which should be [0,0,0] initially, so that the values accumulate correctly. The value to add is under TOS. Returns the modified array. When finished collecing values, use n:running-variance-finalize

running-variance-finalize a -- a
needs math/mean

Finalizes calculations done by n:running-variance, and returns an array with [sample variance, mean, count, population variance, stddev] The original accumulator array is not modified, so this can be used periodically on a data stream to gather interim values.

sgn n -- n'

Returns a -1 if n < 0 , 0 if it is zero, and 1 if n > 0 .


See also: n:cmp n:=
shl n n2 -- n'

Returns the value of n "shifted left" n2 bits. So 1 2 shl returns 4 .


See also: n:shr n:* n:/
shr n n2 -- n'

Returns the value ofn "shifted right" n2 bits. Thus 4 2 shr returns 1 .


See also: n:shl n:* n:/
sin n -- n'

Calculates the sine of n (radians).


See also: n:cos n:tan n:asin
sincos n -- n1 n2 (as of 24.04)

Returns simultaneously the sin and cos of n: n1=sin(n), n2=cos(n)

sind n -- sin(n)
needs math/trigd

Returns the sin of the angle n, specified in degrees.

sinh n -- n' (as of 24.03)

Returns the hyperbolic sine of the input number.

sqr n -- n'

Returns the square of the number, e.g. n dup n:* .


See also: n:sqrt n:*
sqrt n -- n'

Returns the square-root of the number.


See also: n:sqr n:/
tan n -- n'

Calculates the tangent of n (radians).


See also: n:sin n:cos n:atan n:atan2
tand n -- tan(n)
needs math/trigd

Returns the tangent of the angle n, specified in degrees.

tanh n -- n' (as of 24.03)

Returns the hyperbolic tangent of the input number.

trunc n -- n'

Truncate the number n , dropping the fractional part and returning integer part. This means rounding-towards-zero.


See also: n:floor n:round n:ceil
~= n1 n2 eps -- T

Returns true if the two numbers are within eps of each other. Particularly useful for determining if "floating point" numbers are close to each other (rather than testing for absolute equality, which may fail otherwise).


See also: n:= n:cmp

OAuth

Namespace: OAuth
Description: Words for OAuth authentication

word sed/description
auth-string map url post? csec tsec -- sig
needs net/oauth

Actually generate the OAuth signature from the parameters given. See samples/net/twitter.8th for an example.

gen-nonce key token -- key token nonce
needs net/oauth

Generate an OAuth nonce from the given key and token strings.

params key token nonce hashtype -- params
needs net/oauth

From the given key, token, nonce and hashtype, produce a params map.

Object

Namespace: o
Description: Object (OOP)

word sed/description
! o s x -- o (as of 21.01)

Stores the item x by name in the object.

+ o m -- o | o o' -- o (as of 21.02)

Takes the variables in the map or object, and puts them in the object o .

+? o m | o | o o' | o (as of 21.02)

Same as o:+ , but doesn't replace an already existing value.

??? s -- (as of 21.01)

Word invoked by default for an unknown object method.

@ o s -- o x | o a -- o a' (as of 21.01)

Gets the item stored by name in the object. If passed an array, it will return an array of the items stored in the string keys passed in.

class o -- o s (as of 21.01)

Returns the 'class' of this object.

exec o ... s -- (as of 21.01)

Invokes the "method" s in the object. Scans down the stack to find the first object, then looks-up the method in that object and its "supers" until it finds the word. If no object is on the stack, throws an exception.

If the neither that object nor its supers has that method, then if a method called unknown-method exists (in the object or its supers), it is invoked with the name of the method which could not be found; otherwise, it is ignored.

isa o s -- o T (as of 21.01)

Determines whether the object or its supers is of the kind denoted by the string.

method o s w | o m -- o (as of 21.01)

Installs the word as a "method" for the object, under the name s . Invoke it with o:exec . Can also be invoked with a map of names->words to insert all at once.

mutate o -- o (as of 21.01)

Allows the given object to modify methods without affecting other members of its class.

new o s -- o' (as of 21.01)

Creates a new object based on an existing object. The string is the 'type' of the object. If o is null then an blank object is created, with no methods. Otherwise, o' derives from o and contains its methods. If o has a method named ctor , it will be invoked on the new object prior to returning it.

If the name s is null , the item will inherit the original object's name.

"Methods" are object-specific words which are invoked by name, using o:exec .

super -- (as of 21.01)

Within a method, invokes the object's super's method of the same name.

OS

Namespace: os
Description: OS-specific functionality

word sed/description
POSIX -- T (as of 24.03)

Returns true if the OS is "POSIX" (true for all but Windows).

chroot s -- T (as of 22.02)

Changes the root directory accessible to the program to the given directory. Returns true if successful, or false and t:err? on failure. Typically requires program have root access.

Not on Windows, obviously.

devname x -- name (as of 19.06)

Given an open file or a string naming a file, return the device name (EVIOCGNAME). Linux and RPI only.

docker? -- T (as of 22.06)
needs utils/docker

Returns true if we are running inside a Docker instance running a Linux OS, false if not (or if running in a Docker instance running some other OS).

env -- m (as of 20.03)

Returns a (read-only!) map with all the environment variables. Might return null , depending on OS.

lang -- s (as of 19.05)

Returns the language of the user's locale as reported by the OS. The return value should be a 2 or 3 letter language code (ISO 639-1 or ISO 639-2).

locales -- a (as of 21.08)

Returns an array of ["lang", "region"] corresponding to the user's currently preferred locales.

notify m -- (as of 21.02)
needs os/notify

Send a 'desktop notification'. m has keys:

power-state -- (as of 22.01

Returns the best estimate of the system's power status. The map keys are "state" (one of "Battery", "No battery", "Charging" or "Charged), "pct" (the percentage charge, and "secs" (the number of seconds estimated runtime on the charge). The latter two might be "-1" for "not available".

region -- s (as of 19.05)

Returns the region of the user's locale as reported by the OS. The return value should be a 2 letter country code (ISO 3166-1 alpha-2).

waitpid n -- n'

Wait for the process with pid n to finish, returning its return code. If the returned value is -1, then t:err? may have something useful to say.

PDF

Namespace: pdf
Description: PDF Document

word sed/description
bezier pdf pt1 pt2 pt3 pt4 wide color -- pdf (as of 22.03)
Professional version

Draws a cubic Bézier curve on the current PDF page from pt1 to pt2, with control points p3 and p4, in the given (point) width and color.

bezierq pdf pt1 pt2 pt3 wide color -- pdf (as of 22.03)
Professional version

Draws a quadratic Bézier curve on the current PDF page from pt1 to pt2, with control point p3, in the given (point) width and color.

circle pdf pt1 radius wide color fillcolor -- pdf (as of 22.03)
Professional version

Draws a circle on the current PDF page centered at pt1 with radius, in the given (point) width, line color and fill color.

color pdf clr -- pdf (as of 22.03)
Professional version

Sets the text color for subsequent pdf:text invocations.

ellipse pdf pt1 pt2 wide color fillcolor -- pdf (as of 22.03)
Professional version

Draws an ellipse on the current PDF page centered at pt1 with x,y radii pt2, in the given (point) width, line color and fill color.

font pdf s -- pdf (as of 22.03)
Professional version

Sets the font to use, currently restricted to the standard PDF fonts: "Courier", "Courier-Bold", "Courier-BoldOblique", "Helvetica", "Helvetica-Bold", "Helvetica-BoldOblique", "Helvetica-Oblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic", "Symbol", or "ZapfDingbats".

img pdf pt1 pt2 img -- pdf (as of 22.03)
Professional version

Draws an image at pt1, with size pt2. The image could be an img or a file name string. An img is any 8th supported format. Supported formats for an image file are JPEG, PNG, PPM, PGM, and BMP.

line pdf pt1 pt2 wide color -- pdf (as of 22.03)
Professional version

Draws a line on the current PDF page from pt1 to pt2, in the given (point) width and color.

new m -- pdf (as of 22.03)
Professional version

Create a new PDF document in memory, with the options given in the map. The map may contain the meta-data keys creator , producer , title , author , subject , and date . Additional keys may be:

key type description
size pt width and height of PDF document (e.g. page size)
text-color clr the color to use for drawing text (black, by default)
text-size n text size in points (12 by default)
font s the font to use (defaults to "Times-Roman")
page pdf -- pdf (as of 22.03)
Professional version

Creates a new blank page in the PDF and makes it the current page for output.

page-size pdf -- pdf wide high (as of 22.03)
Professional version

Gets the size of the PDF document current page in points.

rect pdf pt1 pt2 wide color fillcolor -- pdf (as of 22.03)
Professional version

Draws a rectangle from pt1, with width pt2.x and height pt2.y, border width wide in color. If fillcolor` is null, don't fill the rectangle; otherwise, fill with that color.

save pdf s -- pdf | pdf f -- pdf | pdf null -- pdf (as of 22.03)
Professional version

Save the PDF. If null , writes to stdout . String or file writes to the named or open file.

size pdf -- pdf wide high (as of 22.03)
Professional version

Gets the size of the PDF document in points.

text pdf s xofs yofs -- pdf (as of 22.03)
Professional version

Write the string at position (xofs,yofs) on the current page in the PDF.

text-rotate pdf s x y angle -- pdf n (as of 23.06)
Professional version

Same as pdf:text , but rotates through the angle (in radians)

text-size pdf n -- pdf (as of 22.03)
Professional version

Sets the size of the font to use.

text-width pdf s -- pdf n (as of 22.03)
Professional version

Calculates the width of the given string using the current font and size. The number returned is points. Returns 0 and sets t:err? if there was an error.

text-wrap pdf s x y w align -- pdf n (as of 22.03)
Professional version

Same as pdf:text , but wraps the text at w points wide, with an text alignment (as listed in the pdf/utils library). Returns the height of the output text (0 on error and t:err? is set).

text-wrap-rotate pdf s x y w align angle -- pdf n (as of 23.06)
Professional version

Same as pdf:text-wrap , but rotates through the angle (in radians)

Pointer

Namespace: ptr
Description: A pointer value, used with the FFI

word sed/description
cast ptr s -- ptr | ptr n s -- ptr (as of 17.07)

When G:unpack is given a "P" to unpack, it doesn't know what the pointer refers to. ptr:cast lets you tell it what the value is, using the same characters as used in ptr:pack . If s is "b", then you must also provide the size n in bytes.

Note: This word has no effect on a ptr whose type is actually known (you cannot coerce a "string" to a "number" for instance).


See also: G:pack G:unpack ptr:pack ptr:unpack ptr:unpack_orig ptr:len
deref -- (as of 24.01

Assuming the ptr is a pointer to something (e.g. void ** ), returns the "n'th" item it points to, e.g. ptr[n] ). May be given a number instead of a ptr, in which case it's assumed to be a raw memory address.

len ptr -- ptr n (as of 17.07)

Returns the number of bytes allotted the contents of this ptr*. For a string or buffer, will be the allocated size.


See also: G:pack G:unpack ptr:pack ptr:unpack ptr:unpack ptr:unpack_orig
null? ptr -- ptr T (as of 21.03)

Returns true if the value of the pointer is 0.

pack x s -- ptr (as of 17.07)

Converts an 8th type x into a ptr suitable for use in the FFI. The string s is one of:

  • "i" for "int"
  • "u" for "unsigned int"
  • "l" for "long"
  • "L" for "unsigned long"
  • "f" for "float"
  • "d" for "double"
  • "p" for "ptr"
  • "w" for "word"
  • "z" for "char *"
  • "b" for a buffer (could be a buffer created by G:pack if you need to pass a pointer to a structure).

See also: G:pack G:unpack ptr:unpack ptr:cast ptr:unpack_orig ptr:len
unpack ptr -- x (as of 17.07)

Inverse of ptr:pack . Convert a ptr back into a normal 8th type.


See also: G:pack G:unpack ptr:pack ptr:cast ptr:unpack_orig ptr:len
unpack_orig ptr -- x (as of 17.07)

Same as ptr:unpack , but returns the original pointer instead of the modified value. For instance, in the "iconv()" function, the destination pointer is modified, making it impossible to retrieve the original value because a buffer has a fixed address which is immutable.


See also: G:pack G:unpack ptr:pack ptr:unpack ptr:unpack ptr:len

PubSub

Namespace: pubsub
Description: Publish/Subscribe messaging framework

word sed/description
publish t msg --
needs utils/pubsub

Enqueues the message msg (which can be any data type) to subscribers of the topic t (a string). The queued message will be dispatched to all subscribers of that topic in the order they subscribed, on the task of the message dispatcher.

qsize n --
needs utils/pubsub

Sets the size of the queue used by the subscribe task. The default is 100

subscribe t wrd --
needs utils/pubsub

Subscribes the word wrd to the topic given by the string t. wrd will be invoked whenever a message is published to that topic. Subscriber SED: \ topic message --

Queue

Namespace: q
Description: FIFO Queue

word sed/description
+ q q2 -- q

Moves as many items as will fit from the queue q2 to the queue q , popping them from one and pushing to the other. If q is not big enough to hold the data from q2 , then it will throw an exception unless q:throwing was false for q .

Modifies both queues.

clear q -- q

Remove all items from the queue.

len q -- q n

Returns the number of items in the queue.

new n -- q

Create a new queue with a maximum capacity n , which must be a positive number. If a negative or zero size is given, returns null . Limited only by available memory.


See also: q:push q:pop
notify q -- q (as of 17.07)

Notifies anyone waiting on that queue that it should awaken and process the data.


See also: G:sleep q:wait t:q-wait t:q-notify
overwrite q T -- q

Set the queue to "overwrite" mode (if T is true ), so that it acts as a circular buffer rather than a queue. This means that continued q:push without q:pop will save the last N items pushed, where N is the size of the queue. If T is false , restore normal queue behavior.


See also: q:push q:pop
peek q -- q x

Same as q:pop but does not remove the item from the queue.


See also: q:pop q:push
pick q ix -- q x (as of 17.04)

Returns the item x at the index in the queue. The front of the queue is 0, item under is 1, etc. If you try to pick beyond the limits of the queue, it will throw an exception.

pop q -- q x

Pop the first item off the queue q , removing it from the queue.


See also: q:push q:peek
push q x -- q

Push the item x into the queue q making it the last item in the queue.


See also: q:pop q:peek
remove q x -- q n (as of 20.01)

Removes all instances of the item x from the queue. Returns the number of instances found and removed.

shift q -- q x

Remove the item x from the back of the queue and put it on TOS. This makes the queue one element shorter. Like q:pop but from the back of the queue.


See also: q:slide q:pop q:push
size q -- q n (as of 16.11)

Returns the size of the given queue, which is the maximum number of items the queue may contain.

slide q x -- q

Add the item x to the front of the queue. Like q:push but at the front of the queue, adding one more element to the queue (q:push puts the item at the back).


See also: q:shift q:pop q:push
throwing q T -- q

If true , the queue q will throw an exception on failure to push or pop. By default, queues throw an exception, because popping from an empty queue is most likely an error, and null is a valid value.

wait q n -- q (as of 17.07)

Waits n milliseconds for a notification on the queue. If n is negative, waits forever. Otherwise, it exits the wait once q:notify is invoked on the queue, or if the timeout expires.


See also: G:sleep q:notify t:q-wait t:q-notify

Rational

Namespace: rat
Description: Rational big-number processing

word sed/description
* r1 r2 -- r1*r2 (as of 19.04)
needs math/rational

Multiply two rationals

+ r1 r2 -- r1+r2 (as of 19.04)
needs math/rational

Add two rationals

- r1 r2 -- r1-r2 (as of 19.04)
needs math/rational

Subtract two rationals

/ r1 r2 -- r1/r2 (as of 19.04)
needs math/rational

Divide two rationals

>n r -- n (as of 20.07)
needs math/rational

Convert a rational to a regular number

>s r -- s (as of 19.04)
needs math/rational

Convert the rational number to its string representation.

new num denom -- rat (as of 19.04)
needs math/rational

Given a numerator and a denominator in integral values (not floats!), produce a new "rational number"

proper r -- n r (as of 19.04)
needs math/rational

Given a (possibly) "improper" rational, e.g. where the numerator is greater than the denominator, convert it to a "proper" pair of whole number and rational remainder. Either or both of the pair may be 0.

Rectangles and points

Namespace: rect
Description: Rectangles

word sed/description
! rect ix n -- rect (as of 22.03)

For a rect or pt, sets the value n at index ix , where 0=x, 1=y, 2=w, 3=h. Does nothing if the index is out of range.

/high rect n -- rect1 rect2 (as of 20.01)

Splits the rectangle into two such that the sum of the heights of the new ones is the same as the height of the original. If n is < 1, it's a ratio of how much of the original should be in the first. Otherwise, it's a pixel size.


See also: rect:/wide
/wide rect n -- rect1 rect2 (as of 20.01)

Splits the rectangle into two such that the sum of the widths of the new ones is the same as the width of the original. If n is < 1, it's a ratio of how much of the original should be in the first. Otherwise, it's a pixel size.


See also: rect:/high
= rect1 rect2 -- rect1 rect2 T (as of 22.02)

Return true if the rectangles are the same.

>a X -- a (as of 22.02)

Converts an X containing the internal rectangle format to an array [x,y,w,h].

>pts rect -- pt1 pt2 (as of 20.01)

Converts the rectangle to its start and end points (upperleft, bottomright) .

>pts4 rect -- pt1 pt2 pt3 pt4 (as of 22.03)

Converts the rectangle to its four corner points (upper left, upper right, lower left, lower right) .

@ rect ix -- rect x | rect a -- rect a' (as of 22.03)

For a rect or pt: if given a number, retrieves the value at index 'x', where 0=xpos, 1=ypos, 2=wide, 3=high. If the index is out of range, 0 is returned. If passed an array, returns an array of the corresponding values.

center rect1 rect2 -- rect3 (as of 22.03)

Creates a new rectangle which is rect2 centered on rect1 .

center-pt rect -- rect pt (as of 20.01)

Returns a point in the center of the rectangle.

intersect rect1 rect2 -- rect' (as of 20.01)

Returns the "intersection" of the two rects passed in. If they don't intersect, a rectangle of [0,0,0,0] is returned.

new a -- X (as of 22.02)

Converts a rectangle which is an array of [x,y,w,h] to internal format.

new-pt a -- X (as of 22.02)

Converts a point which is an array [x,y] to internal format.

ofs rect pt -- rect' (as of 21.01)

Adds the point to the rectangle, moving the rectangle's upper-left by pt .

open rect -- xpos ypos wide high (as of 22.03)

Use instead of a:open , because a rect may be a native value rather than an array.

pad rect pt -- rect2 (as of 20.01)

Pads the rectangle with the [x,y] values from pt . The x value is added to the "x" and "w" components of the rectangle, the y value is added to the "y" and "h" components.

pos rect -- pt (as of 20.01)

Converts a rectangle to a point which is its [x,y] position.

pt-open pt -- xpos ypos (as of 22.03)

Use instead of a:open , because a pt may be a native value rather than an array.

pt>a X -- a (as of 22.02)

Converts an X containing the internal format to a point which is an array [x,y].

pt>rect pt -- rect (as of 22.07)

Converts the point (x,y) into the rectangle (0,0,x,y) .

pts> pt1 pt2 -- rect (as of 20.01)

Returns a rectangle starting at point pt1 and ending at point pt2 . Assumes pt1 is left and above pt2 .

restrict rect1 rect2 -- rect2 (as of 24.04)

Modifies rect2 so that it is completely within rect1 , moving it as appropriate and modifying its size, if necessary.

shrink rect n -- rect' | rect a -- rect' (as of 20.01)

Shrinks (if n is postive) or grows the rectangle by n in all directions. If given an array, it is values by which the rectangle should shrink on each side [left,top,right,bottom]. If n is a number in the range (0..1) then it shrinks the rectangle by that percentage of the width and height.

size rect -- pt (as of 20.01)

Converts a rectangle to an point [w,h] which is its size.

union rect1 rect2 -- rect' (as of 20.01)

Returns the "union" of the two rects passed in: e.g., the bounding box containing both rectangles.

Regex

Namespace: r
Description: PCRE regular-expression

word sed/description
++match r -- r n

Same as r:+match , but matches after the full length of the previous match (instead of just one character past, as r:+match does).


See also: r:new r:match r:+match r:@
+/ s r -- a (as of 18.02)

Same as r:/ but skips past the end of the previous match. So that e.g. "1.2 abc 3.4 def" /([1-9][0-9.]+)/ r:+/ gives ["1.2", "3.4"] , whereas r:/ gives ["1.2", "2", "3.4", "4"] .


See also: r:/
+match r -- r n

Match the regex r against the previously matched string, beginning from just after the previous match. Returns a number n which is the number of matches, or null if there was no prior match.


See also: r:new r:match r:++match r:@
/ s r -- a

Splits the string on a regex and returns an array containing the matches, or null if there were no matches.

Ex: "1234567" /(\d\d\d)(\d\d\d\d)/ r:/ returns ["123","4567"] .


See also: r:@ r:match
@ r n -- r s | r a -- r a'

Returns a string which is match number n from the regex r , or null if there was no match. If given an array of numbers, returns an array of those matches.

Note: do not confuse with G:r@ !


See also: r:new r:match r:+match r:++match
len r -- r n (as of 17.02)

Returns the number of matches currently matched by the regex.

match x r -- r n

Match the regex r against the string or regex x . Returns the number n of matches, which may be 0 if there were no matches, or null if x was neither a string nor a previously matched regex.


See also: r:new r:+match r:++match r:@
match[] x r -- a (as of 25.06)
needs regex/match

Returns an array of all matched values, or null if there were no matches.

matchall[] x r -- a (as of 25.06)
needs regex/match

Same as r:match[] , but returns all matches of the regex over the entire string or regex x .

new s -- r

Create a new regex from the string, or null if it failed to create one.


See also: r:match r:+match r:@
rx r -- r s (as of 17.06)

Returns the string which is the regular-expression represented by the regex, or null if no such string exists.

str r -- r s (as of 17.06)

Returns the string against which the regex r was matched, or null if no such string exists.

Serial

Namespace: sio
Description: Serial I/O

word sed/description
close sio --
Hobbyist version

Closes a previously opened sio, and terminates any connections.


See also: sio:open sio:opts@ sio:opts! sio:enum sio:read sio:write
enum -- a
Hobbyist version

Returns an array of paths to valid serial devices. One of these may be passed to sio:open . Returns null if there are no valid devices.


See also: sio:open sio:opts@ sio:opts! sio:write sio:read sio:close
open s -- sio
Hobbyist version

Returns a sio which represents an opened serial port named by the string, or null if it was unable to do so.


See also: sio:opts@ sio:opts! sio:read sio:write sio:enum sio:close
opts! sio m -- sio
Hobbyist version

Sets the sio's options based on the map (as returned by sio:opts@).


See also: sio:open sio:opts@ sio:read sio:write sio:enum sio:close
opts@ sio -- sio m
Hobbyist version

Returns a map containing the sio's current settings. All known settings will be returned as a key in the map, and all values are either numeric or boolean.


See also: sio:open sio:opts! sio:read sio:write sio:enum sio:close
read sio sb n -- sio sb n'
Hobbyist version

Reads n bytes from the sio, appending to the string or buffer sb . The number of bytes read is left on TOS, or null if there was a problem. The original sb remains on the stack and is (possibly) modified by the read.


See also: sio:open sio:opts@ sio:opts! sio:write sio:enum sio:close
write sio sb -- sio n
Hobbyist version

Writes the string or buffer sb to the sio. The number of bytes written is left on TOS, or null if there was a problem.


See also: sio:open sio:opts@ sio:opts! sio:enum sio:read sio:close

SMTP

Namespace: smtp
Description: SMTP access words

word sed/description
new opts -- smtp T
needs net/smtp

Takes a map opts with network options and returns a new smtp item which is used to communicate with an SMTP server. Immediately tries to connect to the given server, returns true if successful.

send smtp msg -- smtp T
needs net/smtp

Sends the message msg to the SMTP server smtp. The message is a map with "from", "to", "cc", "bcc" keys -- which may be single strings or arrays of string. "subject", "body" are required and must be strings. Returns true on success, or false and sets the "err" key.

SOAP

Namespace: SOAP
Description: SOAP

word sed/description
call map -- xml|errs
needs net/soap

Performs a SOAP call based on the information in the given map. See samples/net/soap.8th for how it's used.

Solver

Namespace: slv
Description: Constraint solver

word sed/description
@ slv x -- slv (as of 21.01)

Gets the value of the variable x ; x is either a string or a number.

auto slv T -- slv (as of 21.01)

If true , turn automatic update of variables on.

build m -- slv (as of 21.01)

Creates a new solver set up according to the map. Keys are:

key description
vars map; each key is a variable name, whose value is the initial value
constraints array of strings with calculation constraints
constant slv x n -- slv (as of 21.01)

Adds a constant n to the constraint x . x is either a string or a number.

constraint slv n -- slv n' (as of 21.01)

Creates a new constraint for the constraint-solver. Returns the index of the constraint. The number n is the strength of the constraint, as defined in the slv/contraint library.

dump slv -- slv (as of 21.01)

For debugging: dumps the state of the solver.

edit slv s str -- slv | slv n str -- slv (as of 21.01)

Adds an edit to the variable, with strength str .

named-variable slv s -- slv n (as of 21.01)

Creates a new named variable for the constraint-solver. Returns the index of the variable.

new -- slv (as of 21.01)

Creates a new constraint-solver.

relation slv x n -- slv (as of 21.01)

Adds a relation n to the constraint x . One of 1 (<=), 2 (=), or 3 (>=); x is either a string or a number.

reset slv T -- slv (as of 21.01)

Resets the solver. If T is true , remove all the constraints.

suggest slv x n -- slv | slv a1 a2 -- slv (as of 21.01)

Adds a suggested value for the variable x , using the value n . If x is a string or a number, n must be a number. If x is an array, then it must contain indices or names of the variables whose values are in the array n .

term slv x1 x2 n -- slv | slv n1 n2 n -- slv (as of 21.01)

Adds a term to the constraint x1 , using the variable x2 and a multiplier n . The "x" values can be strings (the names of the constraint or variable) or a number (index of the constraint or variable).

update slv -- slv (as of 21.01)

Makes the slv update the variables, if slv:auto was not set true .

v[] slv -- slv a (as of 21.01)

Returns an array of the values of all variables in the solver, in order of insertion.

variable slv -- slv n (as of 21.01)

Creates a new variable for the constraint-solver. Returns the index of the variable.

v{} slv -- slv m (as of 21.01)

Returns a map of the values of all named variables in the solver.

Sound

Namespace: snd
Description: Playing and recording sounds

word sed/description
apply-filter x -- snd2 (as of 18.06)
Hobbyist version

Applies the filter created by snd:filter to the playback device. If null, all filters are removed. Multiple filters may be simultaneously applied.


See also: snd:filter
devices? -- a (as of 18.06)
Hobbyist version

Returns an array of supported sound devices on the current system.

end-record X -- (as of 18.03)
Hobbyist version

Stops the audio recording.


See also: snd:record
filter m -- X (as of 18.06)
Hobbyist version

Creates a new biquad filter based on the parameters given in the map. The result may be used with snd:apply-filter to affect playback.

Possible keys are:

  • "kind", which is one of the following:
  • "biquad" : values are "a0", "a1", "a2", "b0", "b1", "b2" -- coefficients for a biquad filter (see miniaudio)
  • "low1" : low-pass filter: "freq"
  • "low2" : low-pass filter: "freq", "Q"
  • "low" : low-pass filter: "freq", "order"
  • "hi1" : high-pass filter: "freq"
  • "hi2" : high-pass filter: "freq", "Q"
  • "hi" : high-pass filter: "freq", "order"
  • "notch" : notch filter: "freq", "Q"
  • "band" : band-pass filter: "freq", "order"
  • "peak" : band-pass filter: "freq", "gain", "Q"
  • "loshelf" : low-shelf filter: "freq", "gain", "slope"
  • "hishelf" : high-shelf filter: "freq", "gain", "slope"

See also: snd:apply-filter
freq snd n -- snd (as of 18.06)
Hobbyist version

For a snd created with a frequency (a number, generating a continuous sine wave tone), this changes its frequency.

gain snd n -- (as of 18.06)
Hobbyist version

Sets the gain of the snd to n , which defaults to 1.

gain? snd -- snd n (as of 18.06)
Hobbyist version

Returns the gain of the snd.

init -- T (as of 19.09)
Hobbyist version

Ensures the sound system is running. Returns false if not. See "libs/snd/loaded" for details.

len snd -- snd n
Hobbyist version

Returns the length of the sound in seconds. This may be used on a snd whether it is playing currently or not.

loop snd T -- snd
Hobbyist version

If T is true , makes snd repeat continuously. Otherwise, makes it play just once (the default).

loop? snd -- snd T (as of 20.01)
Hobbyist version

Returns true if the sound is supposed to loop when done playing.

mix snd -- (as of 18.06)
Hobbyist version

Plays the snd, mixing it with other sounds in the mixer queue.

new x -- snd
Hobbyist version

Creates a new snd. If passed a:

  • string: it must be a valid audio file-name
  • buffer: it must be valid audio data
  • number: it is a frequency for a continuous sine-wave tone
  • array: it is [kind,amplitude,frequency] for a tone, where 'kind' is 0 for sine, 1 for square, 2 for triangle, 3 for sawtooth. Or [kind,amplitude] where 0 is 'white-noise', 1 is 'pink-noise', and 2 is 'brownian-noise'.
  • word: it is a custom sound which is implemented by that word, whose SED is n1 n2 -- b , where n1 is the number of 32-bit float frames required, n2 is the number of channels, and b is a buffer containing the floating-point sound data.

To play the sound, invoke snd:play , passing it the snd item. Returns null if the sound format is not supported or the sound is otherwise unplayable.

Note: you must invoke requires sound first!

Note: only WAV, MP3, FLAC, and OGG formats are supported.


See also: snd:play snd:stop snd:volume
pause snd T -- snd (as of 18.08)
Hobbyist version

If snd is playing, stops the playback if *T is true, otherwise resumes playback of the sound. When snd:play or snd:mix is invoked on this sound, it will resume playback from where it stopped. This only works with sounds played from files.

play snd --
Hobbyist version

Plays the snd created by snd:new .


See also: snd:volume snd:new snd:stop
played snd -- (as of 18.03)
DEFFERED
Hobbyist version

Invoked when the snd has finished playing.

rate snd n -- snd
Hobbyist version

Set the sample rate of the snd.

ready? -- n1 n2 (as of 20.01)
Hobbyist version

Returns the number of sounds: currently playing n2 , and enqueued to be played n1 . Returns null if snd:init hasn't been invoked yet.

record s -- X | m -- X (as of 18.03)
Hobbyist version

Starts recording audio at 44.1KHz, 32-bit floating pt, WAV format, into the file named by the string. The return value may be used to control the recording. When X is refcounted to 0, the recording will stop. You may also use snd:end-record to explicitly stop recording. null will be returned if the recording could not be started for any reason.

If given a map, then it contains some of the keys:

key type description
data w: m b -- invoked for each captured buffer of 4-byte IEEE float data
done w: m -- invoked when snd:end-record is
init w: m -- invoked before starting recording
channels n How many channels of audio to record (default: 2)
format n 0-5, one of the miniaudio audio formats
rate n sample ratge

See also: snd:end-record
resume -- (as of 20.01)
Hobbyist version

Resumes sound playback.

seek snd n -- snd (as of 18.08)
Hobbyist version

For a sound which is initialized from a file or buffer, sets the next play position to the n 'th PCM frame.

stop snd --
Hobbyist version

Stops that sound from being played.


See also: snd:volume snd:new snd:play
stopall -- (as of 18.03)
Hobbyist version

Stops all sound playback.


See also: snd:resume
volume n --
Hobbyist version

Sets the system sound volume to a value between 0 and 1, where 1 is 'full volume'.


See also: snd:new snd:play snd:volume?
volume? -- n
Hobbyist version

Returns the system sound volume as a number between 0 and 1, where 1 is 'full volume'.


See also: snd:volume snd:new snd:play

Stack

Namespace: st
Description: Fixed-size stack

word sed/description
+ st st2 -- st | null st2 --

Moves as many items as will fit from the stack st2 to the stack st , popping them from one and pushing to the other. If st is null , the data-stack will be the destination.

If st is not big enough to hold the data from st2 , then it will throw an exception unless st:throwing was false for st . If st is not null , it will remain on TOS; otherwise it is removed.

Modifies both stacks.

. st --

Print the top st:dot-depth items of the given stack, in the same manner that G:.s does for the data stack.


See also: G:.s st:dot-depth
clear st -- st

Removes all the items currently on the given stack. Functionally equivalent to invoking repeat st:pop drop st:len while! .

Note: to clear the main data-stack, use G:reset rather than st:clear !


See also: G:reset
dot-depth -- v (as of 24.02)

Variable containing the maximum depth of stack items to print with st:. (and .s and .r ) as well as st:list .


See also: G:.s st:.
len st -- st n

Returns the number of items currently on the given stack.

list st n -- a (as of 24.02)

Returns an array of strings, at most n long, of items on the given stack. Used by .s etc. to print the stack. Useful if you want to G:log the current stack. The strings are "escaped" so that e.g. a "\r" character displays as \r rather than causing truncation of the output.

If the array is not empty, the first item is a number, the depth of that stack.


See also: G:.s st:.
ndrop st n -- st (as of 18.03)

Drops n items from the given stack.

new n -- st

Create a new stack of capacity n . The value given must be a positive non-zero number; if it is not, null is returned.

op! st w -- (as of 18.04)

Invokes w on the TOS of stack, replacing it. Any operands to w should appear in their normal stack order under st . The SED for w is x--x' .


See also: G:rop!
peek st -- st x

Peeks at the top of the given stack without removing the top item. Returns that item from the stack or null if empty.


See also: st:throwing st:push st:pop
pick st n -- st x

Same as G:pick for the specified stack.


See also: G:pick G:rpick
pop st -- st x

Pops the item x from the given stack. If the stack is empty, throw an exception, unless st:throwing was set false , in which case it returns null .


See also: st:throwing st:push st:peek
push st x -- st

Push the item x onto the given stack. If the stack is full, throw an exception unless st:throwing was set false , in which case it fails quietly.


See also: st:throwing st:pop st:peek
roll st n -- st

Same semantics as G:roll for the specified stack.


See also: G:roll G:rroll
shift st -- st x

Remove the item x from the bottom of the stack and put it on TOS. This makes the stack one element shorter, and shifts all remaining elements one lower. Like st:pop but from the bottom of the stack.


See also: st:slide st:pop st:push
size st -- st n (as of 16.11)

Returns the size of the given stack, which is the maximum number of items the stack may contain.

slide st x -- st

Add the item x to the bottom of the stack, moving all remaining items up one index. Like st:push but at the bottom of the stack.


See also: st:shift st:pop st:push
swap st -- st

Same as G:swap , but for the specified stack. That is, it exchanges TOS of the given stack with the item below it.


See also: G:swap
throwing st T -- st

If true , make the stack st throw an exception on failure to push or pop; otherwise, the stack will return null on error. By default stacks throw on failure.

String

Namespace: s
Description: Arrays of UTF-8 encoded characters

word sed/description
! s ix n -- s'

Replace the character at index ix in the string with the Unicode character n . If ix is greater than s:len-1 , nothing will happen. If it is negative, the character that is that many characters from the end of the string will be modified (-1 is the last character).

Ex: "abcdef" 3 'X s:! results in "abcXef"


See also: s:@
* s n -- s'

Creates a new string by replicating the initial string s n times. If n is 0 or negative, an empty string is returned.


See also: s:+
+ s s2 -- s' | s n -- s'

Appends the string s2 to s . If a number is given instead, it is treated as a Unicode character.


See also: s:append
- s ix n -- s'

Remove n characters from the string s , starting at character offset ix . Both n and ix must be positive numbers, and if the combined length is greater than the string length then nothing is done.

/ s n -- a | s a1 -- a2 | s pat -- a | s null -- a

Split the string s at n , splitting into an array [head,tail] at that character index (starting from 0).

If an array of numbers a1 is given, splits into an array of strings with that many characters each, repeating the last value as long as there is still something to split (e.g. "12345" [2] s:/ will give ["12","34","5"] ).

If string or a regex pat is given, splits on all occurrences of pat , omitting it from the results.

If null is given, splits s into its component characters.

Returns an array of results, or an array with the entire string as the only element, if there are no matches.


See also: b:/ a:join
/scripts s -- a

Breaks the string into an array of runs of characters with the same script and direction characteristics (LTR vs RTL).


See also: s:script?
/ws s -- a (as of 24.05)

Same as s:trim /\s+/ s:/ , but more concise.

<+ s s2 -- s' | s n -- s' (as of 16.08)

Prepends the string or Unicode character to the string.

<> s ix1 ix2 -- s' (as of 22.07)

Swaps the string characters at those indices. Ex: "abc" 1 2 s:<> returns "acb" . Negative indices count from the end of the string.

= s1 s2 -- T

Compare the strings s1 and s2 , returning true if they are the same UTF-8 bytes, otherwise false . This implies that if a character is improperly encoded it will not compare as equal to its properly encoded counterpart.


See also: s:cmp s:cmpi
=ic s1 s2 -- T (as of 16.12)

Same as s:= , but ignores case differences.


See also: s:= s:cmp
>base64 s -- s'

Encode a string in base64 encoding.


See also: s:base64>
>ucs2 s -- b (as of 17.04)

Converts the string to its UCS2 representation.

@ s ix -- s n

Returns the Unicode character n at index ix in the string. If ix is greater than the number or characters in s , null is returned instead of a character. If ix is negative, the character that far from the end of the s will be returned (-1 is the last character).

Ex: "abcdef" -2 s:@ returns the character "e" (e.g. 101).


See also: s:!
append s1 s2 -- s1 | s n -- s (as of 18.04)

Same as s:+ , but, modifies the original string rather than creating a new one.

base64> s -- s'

Decode a string from base64 encoding.


See also: s:>base64
clear s -- s

Overwrites the contents of s with 0, and resets its length to 0.

Note: this modifies the original string itself!


See also: b:clear
cmp s1 s2 -- n

Compare two strings, returning n which is -1 if s1 < s2 , 0 if they are the same, and 1 if s1 > s2 .


See also: s:cmpi s:=
cmpi s1 s2 -- n

Same as s:cmp , but compares in a case-insensitive manner.


See also: s:cmp s:=
compress s -- s'

Compress a string using "zlib".


See also: s:expand
count-match s s1 -- s n (as of 22.06)

Returns the number of non-overlapping times the string s1 occurs within s .

days! short long --

Takes two arrays: short , containing the short names of the week-days, and long containing the long names of the week-days, and inserts them into the appropriate maps for localization according to the current value of G:curlang . Should be used in the appropriate "lang/xx" asset.


See also: G:long-days G:short-days
dist s1 s2 T -- n (as of 20.07)

Return the "Levenshtein" distance between the strings (number of insertions, deletions, and transpositions to convert one to the other). If T is true , performs folding first to eliminate diacritics and case differences.

each s w --

Invokes w for each character of the string. w 's SED is: ix n -- The number ix is the index of the character in the original string. n is the character's Unicode encoding.

Modifying the string while it is being iterated may throw an exception. Use s:map if you want to do that.


See also: s:each!
each! s w -- (as of 19.04)

Same as s:each , but only passes the Unicode character, omitting the index, to the word. The SED of w is: n -- .

Note: Modifying the string while it is being iterated may throw an exception. Use s:map if you want to modify the string.


See also: s:each
eachline sb w --

Invokes the word w for each line of the input string or buffer, passing that line in TOS. Lines are simply CR or CRLF or LF delimited runs of characters. The SED of w is: s -- . Responds to break .

NOTE: the same actual string is passed to the callback, so if you want to store the data you need to clone it (or use const ).


See also: s:each
escape s1 s2 s3 -- s' (as of 19.08)

Given a source string, a string of characters s2 to escape, and a string indicating a character or string of characters s3 to use as the escape character, returns a string which consists of the original with all instances of any of the characters in s2 escaped.

Ex: "abcd" "bc" "\\" s:escape will result in "a\b\cd" .

expand s n -- s'

Expand a "zlib"-compressed string, where the number n is the original size of the uncompressed string. If the original size is not known, pass 0 for n .


See also: s:compress
fill s rep -- s' | s n -- s'

Fill the contents of the s with string rep or with the Unicode point n . rep is repeated until s' is filled without extending the length of s.


See also: b:fill
fold s T -- s' (as of 20.07)

Lowercases the string, removing diacritics if T is true . Unicode-aware.

gen-uid n -- s (as of 24.02)
needs rand/ident

Create a string of random characters, suitable for an identifier. The first character is chosen from a limited palette so the result should not be confused with a number. The first character is randomly chosen from among 19 characters; the rest are randomly chosen from 36. It uses the cr:rand word to shuffle the characters.

globmatch s1 s2 -- T (as of 16.02)

Using the f:glob matching algorithm, compares the two strings. Returns true if they match.


See also: f:glob f:rglob
hexupr T --

Controls how hexadecimal numbers are converted to strings. If T is true , then hex numbers will be uppercase. The default is false (e.g. lowercase).

insert s1 s2 ix -- s3

Insert the string s2 into the string s1 at offset ix , which must be a positive number. If ix is greater than the current number of characters in s1 , then s2 will be appended to s1 . Similarly, if it is 0 or less, s2 will be prepended to s1 .

intl s -- s'
needs string/i18n

Returns the translation of the string, based on the language set by s:lang . If no translation was given, the original string is returned, otherwise the translated string is returned.


See also: s:lang s:intl! G:curlang
intl! m --
needs string/i18n

Sets the map to use for translating strings for the language G:curlang.


See also: s:lang s:intl G:curlang
lang s --
needs string/i18n

Set the current language for s:intl to the string s, which is the name of a sub-asset. For example, if the language is given as "de", there must be an asset called lang/de . That asset consists solely of a JSON map whose keys are the untranslated strings, and whose values are the translation of the key into the requested language.

If the requested language asset does not exist, the current language is not changed.


See also: s:intl s:intl! G:curlang
lc s -- s'

Convert the string s to lowercase. Understands Unicode case conventions. If it is a number, returns the corresponding lowercase Unicode point as a number.


See also: s:uc
lc? s -- s T | n -- n T (as of 20.07)

Returns true if given a "lowercase" Unicode character. If given a string, only the first character is tested.


See also: s:uc s:lc s:uc?
len s -- s n

Returns the length of the string in characters it currently contains (takes UTF-8 into account, so may be less than what s:size reports).


See also: s:size
len' s -- n (as of 24.03)

Same as s:len but does not leave the string on the stack.

len2 s1 s2 -- s1 s2 n1 n2 (as of 24.03)

Given two strings, returns their respective lengths (of characters, not bytes). Much faster and more efficient than the hard way.

lsub s n -- s'

Returns the leftmost n characters of the string. If n is negative, ends that many characters from the end of the string. Ex: "abcde" 2 s:lsub returns "ab", and "abcde" -2 s:lsub returns "abc".


See also: s:rsub
ltrim s -- s'

Remove whitespace from the left end of the string.


See also: s:rtrim s:trim
map s w -- s'

Create a string whose elements are formed by executing the word w for each character of the original string. The SED of w is n -- x , meaning it gets a Unicode character and may modify it. It must return one of a:

  • number: a Unicode character to replace n
  • string: likewise replacing n
  • boolean: if true , keep n ; otherwise omit it
months! short long --

Takes two arrays: short , containing the short names of the months, and long containing the long names of the months, and inserts them into the appropriate maps for localization according to the current value of G:curlang . Should be used in the appropriate "lang/xx" asset.


See also: G:long-months G:short-months
n> n -- s | a -- s (as of 22.02)

Converts a single number, or an array of numbers, representing Unicode code points, to a string.

new n -- s | s -- s' | b -- s (as of 18.05)

Creates a new string s . If given a:

  • number: returns an empty string capable of holding n bytes
  • string: returns its clone
  • buffer: returns a string containing its bytes (like >s )
norm s n -- s' (as of 20.07)

Normalizes the string in the manner specified by n :

  • 18: NFD (decompose)
  • 10: NFC (compose)
  • 22: NFKD (decompose compatible)
  • 14: NFKC (compose compatible) or use the constants defined in the strings/normal library
reduce s w x -- x' (as of 19.07)

Analogous to a:reduce . Iterates the string, passing w the accumulating value x and the character at each index. SED of w is x n -- x' , where n is the Unicode character.

repinsert s n s2 -- s'
needs string/repinsert

Inserts the string s2 inside s every n characters. Example: "abcdef" 2 "xx" s:repinsert results in "abxxcdxxef"

replace s pat rep -- s'

Create a new string by replacing the pattern pat , just once, with the string rep . pat can be a string or a regex, and is replaced only once. To replace all, use s:replace! .


See also: s:replace!
replace! s pat rep -- s'

Same as s:replace , but replaces all occurrences.


See also: s:replace
rev s -- s'

Returns the string with its characters in reverse order. It is semantically the same as null s:/ a:rev "" a:join but faster, and uses only enough memory to store the new string.

rsearch haystack {ofs} needle -- haystack n

Same as s:search , but returns a number which is the offset of the last occurrence of needle in haystack . Returns null if there is no match.


See also: s:search
rsub s n -- s'

Returns the rightmost n characters of the string. If n is negative, starts from the left side of the string.


See also: s:lsub
rtl s -- s' (as of 24.03)

Does an "RTL fixup" on the string, swapping position of any RTL (Hebrew/Arabic, etc) so they draw correctly.

rtrim s -- s'

Remove whitespace from the right end of the string.


See also: s:ltrim s:trim
scan-match s s1 s2 -- s ix (as of 22.06)

Scans the string and returns the offset of the instance of s2 which matches s1 . That is to say, s1 and s2 are matched in number of occurrences. This is primarily used to parse strings containing code (e.g. CSS or the like) where a character (or a string tag) is used to delimit chunks of code. null is returned if no matching values were found, otherwise the character offset of the start of s2 is returned.

script? s -- s m

Returns information about a string's scripts and directionality in a map. The "dir" key will be either "LTR" or "RTL". The "script" key in the map returned will be one of "mixed", "latin", "greek", "cyrillic", "armenian", "hebrew", "arabic", "syriac", "thaana", "nko", "indic", "cjk", "number", "whitespace" or "symbol". If "mixed", then more than one script is present in the string.


See also: s:/scripts
search haystack needle -- haystack n | haystack ofs needle -- haystack n

Search the string haystack for the first occurrence of the string or regex or number needle , returning the numeric offset in the string of the found text, or null if not found. If needle is a number, it is treated as a Unicode character. If ofs is given, it is a number which indicates at which offset in characters within haystack to start searching from (a negative offset counts from the end of the string).


See also: s:rsearch b:search
size s -- s n

Returns the size of the string in bytes. Not necessarily the same as the number of characters given by s:len , since strings are UTF-8 encoded.


See also: s:len
slice s ix n -- s'

Returns a new string representing a "slice" of the string s , beginning at the position ix for n characters (not bytes!). A negative value of ix means "from the end of the string". If ix is beyond the end of s , null is returned. A negative value of n means "take the rest of the string".


See also: b:slice
soundex s -- s' (as of 20.07)

Returns a "Soundex" code for the given string. Handles diacritics by ignoring them.

strfmap m a m2 -- m s
needs string/strfmap

Utility to format like s:strfmt does, but taking named keys from the a array and pulling the values from the map m2. Still positional, unlike s:tsub.

strfmt a fmt -- s | x1 x2 ... xn fmt -- s

Like the "printf" function in C. Takes a string fmt containing formatting characters, and either an array containing the items to interpolate into the result string, or items x1 , x2 , etc. on the stack corresponding in number to the items to be interpolated. The formatting is done by taking a % inside fmt to mean "format an item from the stack or array, right here". A literal % character is given by %% . Valid formatting codes are:

char format
b buffer
c Unicode code point, or the first character of a string
d integer
f float
g float with exponent
p pointer (number, word, or ptr)
s string
x hex integer

Width, filler, and alignment options precede the format character:

char description
* next char is the 'filler'
, next char is the 'thousands separator'
0 zero-pad the number
< left-align
> right-align
@ preceding digits are the base to use for this number
\
n.m field width of 'n' characters, 'm' after decimal (optional)

Ex: 123 "%*-5d" s:strfmt . prints --123 .


See also: G:.# G:n# G:c# s:strfmt G:,# G:e#
term s n -- s' (as of 22.07)

Ensure the string s is terminated by the Unicode point n . Returns a new string, only adds n if the string is not already terminated with it. Ex: "abc" 'x s:term returns "abcx" .

text-wrap s font n -- a (as of 20.01)

Takes a string and breaks it into sections which will display in an area at most n pixels wide, using the font. If font is null , then n is a maximum width of characters (rather than pixels). The string will be separated on word boundaries, if possible, and leading whitespace removed. The resultant array will have at least one string in it. If s cannot be 'wrapped' in the given width, it will be the sole entry in a .

tr s1 s2 s3 -- s (as of 23.08)

Translate the characters in s1 according to the translation provided between s2 and s3 , where each character of s2 , if it appears in s1 , is converted to the corresponding character in s3 .

The length (in characters) of s2 and s3 must be the same and non-zero, otherwise the original s1 is returned.

translate s1 s2 s3 -- s (as of 22.05)
needs string/translate

Translate the characters in s1 according to the translation provided between s2 and s3 , where each character of s2 , if it appears in s1 , is converted to the corresponding character in s3 . Example: "abbc" "abc" "123" s:translate returns "1223" NOTE: this is deprecated: use s:tr instead.

trim s -- s'

Remove whitespace from both ends of the string.


See also: s:ltrim s:rtrim
tsub s x -- s'
needs string/tsub

Takes a string with replacement parameters such as %0%, %1% or %name%, %address%, and values x in an array (if using %0% etc) or map (if using %name% etc) containing items to replace the parameters in s. The sequence "%%" in s produces a literal "%" in the new string. If the value being substituted is a word, it is invoked and the result is used as a substitute. Otherwise, the item is converted to a string and inserted.

uc s -- s'

Convert the string s to uppercase. Understands Unicode case conventions. If it is a number, returns the corresponding uppercase Unicode point as a number.


See also: s:lc
uc? s -- s T | n -- n T (as of 20.07)

Returns true if given an "uppercase" Unicode character. If given a string, only the first character is tested.


See also: s:uc s:lc s:lc?
ucs2> b -- s (as of 17.04)

Converts from a UCS2 representation to the UTF8 string.

utf8? s -- s T (as of 16.11)

Determines if the string is a valid UTF-8 sequence or not. Returns true if it is valid UTF-8, false otherwise.

zt s -- s

Ensure the string s ends with NUL (ASCII zero) and adjust its length if needed. Not generally needed, but if you convert from an external buffer (e.g using G:unpack ) or you need to pass a string to an external (e.g. system) library, you may need this, because 8th strings are not always NUL terminated.

Structures

Namespace: struct
Description: Interface for easy FFI structures

word sed/description
>buf str -- str buf | throw
needs utils/structs

Converts a struct to a buffer.

arr> str1 buf -- str2 | throw
needs utils/structs

Using the struct str1 as a pattern, and an array arr of data, create a new struct str2.

buf str len --
needs utils/structs

Create a field of type "buffer" ("len" bytes, or if "0" as many bytes as the buffer or string) with the given name.

buf> str1 buf -- str2 | throw
needs utils/structs

Using the struct str1 as a pattern, and a buffer buf of encoded data, create a new struct str2.

byte str --
needs utils/structs

Create a field of type "byte" (1 bytes integer) with the given name.

double str --
needs utils/structs

Create a field of type "double" (8 bytes) with the given name.

field! str fld val -- str
needs utils/structs

Using the struct str, the name of a field fld, and the value of that field val, store the value in the struct.

field@ str fld -- str val
needs utils/structs

Using the struct str and the name of a field fld, get the value of that field val.

float str --
needs utils/structs

Create a field of type "float" (4 bytes) with the given name.

ignore str num --
needs utils/structs

Create a field to ignore num bytes (e.g. skip that many bytes).

int str --
needs utils/structs

Create a field of type "int" (4 bytes) with the given name.

long str --
needs utils/structs

Create a field of type "long" (8 bytes) with the given name.

struct; str --
needs utils/structs

End the definition of a "struct", creating a new word which when invoked will put the empty struct on TOS.

word str --
needs utils/structs

Create a field of type "word" (2 bytes integer) with the given name.

Task

Namespace: t
Description: Task (Thread)

word sed/description
! x s -- (as of 17.06)

Stores the value x into the task-local variable named by the key s .


See also: t:@ w:! w:@
@ s -- x | a -- a' (as of 17.06)

Returns the value of the task-local variable named by the string. If passed an array, returns the named values.


See also: t:! w:! w:@
by-name s -- a (as of 19.08)

Returns an array of the task(s) named by the string. null is returned if no matching tasks were found.

curtask -- t (as of 16.11)

Returns the identifier for the current task.

def-queue n --

Sets the default size of the queue to give new tasks to n , which must be between 1 and 100000. The default is 8.

def-stack n --

Sets the size of the stack to give new tasks to n , which must be at least 16. The default is 8192 on mobile, and 131072 otherwise. The default data stack size is set using G:stack-size .

done? t -- t T

Returns true if the task is done (meaning that the word used to run it has finished). Returns false as long as that word continues running.

dtor w -- (as of 21.09)

Sets a word invoked when the task terminates. Not on Windows.

err! n s -- (as of 19.01)

Sets the value to be returned from t:err? . The parameter n is a number error code, where 0 is considered 'no error' and s is a string which describes the error.


See also: t:err?
err? -- m (as of 19.01)

Returns a map containing "errno" and "msg", which are the integer error code, and a text representation of it, of the last error which occurred in the current task.


See also: t:err!
errno? -- m (as of 19.04)

Sets the task error according to the current value of "errno", and returns the map with the error information just as t:err? does.


See also: t:err?
extra -- x (as of 23.05)

Gets the task-specific 'extra' value, used internally; but for net:server et. al. returns the net that task is handling.

getq -- q (as of 17.07)

Gets the current task's queue.

handler w -- (as of 18.07)

Install an exception handler for a task. w has the SED x -- n , where 'x' is information about the exception (usually a string, but any item can be thrown). The number n is one of:

  • 0: not handled by w , so invoke G:handler
  • 1: ignore and continue
  • 2: terminate this task (if REPL task, app is terminated)
  • 3: restart the task (if not REPL task)
  • 4: resume at another word w2 , in this case the SED is x -- w2 n
  • 5: show a dialog (or console message) and quit afterwards (the default for GUI apps)

Any value other than those will invoke the default handler. The default is 0.

handler@ -- w (as of 20.05)

Returns the current value of t:handler

kill t n --

Kill the task, waiting n seconds before forcibly killing it. A negative number means 'wait forever' as for G:sleep .

Note: the timeout is not implemented for Android.


See also: t:task t:task-n
list -- a (as of 17.08)

Retrieves a array of tasks which are currently "alive". Might not be valid at any subsequent time.

main -- t

Returns the identifier for the REPL, or main, task (there is always at least one task, which the main interpreter runs on).

max-exceptions n -- (as of 20.01)

Allows up to n exceptions to occur on the current task within 100 msec, before it is killed. A value of 0 or less means "allow any number of exceptions". The default value is 10.

name! s -- (as of 17.08)

Sets the name of the current task.

name@ -- s (as of 17.08)

Gets the name of the current task.

notify t --

Notify the task t to stop sleeping.


See also: t:wait t:q-wait G:sleep
parent -- t (as of 19.08a)

Returns the task which launched the current one.

pop -- x

Pops an item (or null if there is no item on the queue and false q:throwing had been invoked on the queue) from the current task's queue. This must be done within the word defining the task (or from one invoked by it).


See also: t:task t:push
priority t n --

Set the priority of the task t to n . The priority is a number from 0 (lowest) to 10 (highest). 5 is the normal value.

push t x --

Pushes the item onto the task's queue. The size of that queue is determined by t:def-queue . The item pushed can be retrieved only by the task itself, using t:pop .


See also: t:task t:pop
push! t x -- (as of 22.06)

Pushes x onto the task's queue and notifies the task. Equivalent of _dup t:push t:notify but much more efficient. Notifies the task and the queue, so waiting with either -1 sleep or -1 t:q-wait will work.


See also: t:task t:pop t:push
q-notify t -- t (as of 17.07)

Notifies the queue of the task that data awaits. Same as q:notify for the task-queue.


See also: G:sleep q:notify t:wait t:q-wait
q-wait n -- (as of 17.07)

Waits n milliseconds for the current task's queue to contain something. Same as q:wait for the task-queue. Requires a corresponding t:q-notify on its task to wake it up and check its queue.


See also: G:sleep q:notify t:wait t:q-notify
qlen -- n

Returns the number of items in the current task's queue.

result t -- t x

Returns the last value x the task put on TOS (when it finished). The value will be null until the task is finished (and might be null after, depending on what's on TOS). Check for the task having finished using t:done? .

set-affinity n -- | a -- (as of 19.05)

Attempts to set the CPU affinity for the current task to the CPU number n . If passed an array of numbers, sets the affinity to the set of CPUs.

setq q -- (as of 20.01)

Sets the current task's queue, moving items from the current queue to the new one.

task w -- t | m -- t

Create a new "task", which is an independent thread of execution. It receives its own data stack and invokes the word you provide as its its starting point. When that word exits, the task goes away.

You may also pass a map instead of a word, in which case the keys are:

key description default
auto automatically decref task when xt done false
name the name to assign the new task name of xt
num the number of items to transfer from the stack to the new task 0
qsize the size of the task's queue 8
stack the size of the recursion stack 128K
xt the word to execute (required)

The word t:task-n can be used if you want the "num" option without specifying all the rest.


See also: t:task-n
task-n xn... x2 x1 n w -- t | xn... x2 x1 m -- t

Same as t:task , except that it takes a number of items to transfer from the current task's stack to the new task's stack. If TOS is a map, then the key "num" has the same role as n .


See also: t:task
task-stop --

Terminates the running task, with prejudice. Normally, a task terminates when the word passed to t:task ends.

ticks -- n (as of 23.04)

Returns how many "ticks" (e.g. d:ticks ) the task has been running.

wait t -- | a -- (as of 17.06)

Waits for the single task (or array of tasks) to complete. If an array, waits for all tasks in the array to complete.

Tree

Namespace: tree
Description: Tree data structures

word sed/description
add tree x -- tree (as of 20.07)

Adds the item x to the tree.

binary w -- tree (as of 20.07)

Creates a new binary-search-tree with a word which implements the comparison function. The tree is implemented as a balanced AA-tree.

bk w n -- tree (as of 20.07)

Creates a new BK-tree with a max distance n (for the metric function) and a word which implements the metric. The metric's SED is tree x1 x2 -- tree n , and must obey the rules for a "metric function":

  • w(x1,x2) >= 0 and integer
  • w(x1,x2) == w(x2,x1)
  • w(x1,x2) == 0 means x1 == x2
  • w(x1,x2) <= w(x1,x3) + w(x3,x2)

A typical implementation of w might be ( true s:dist ) , which folds the strings it's passed and uses Levenshtein distance as the metric. Of course, this can only apply if the items in the tree are strings (which is typical for a BK tree).

The n parameter limits how large the value returned from the metric is allowed to be. Values larger than it will be clamped. This prevents the tree growing beyond reason.

btree w n -- tree (as of 21.04)

Creates a new BTREE of order n , with a word implementing the comparison function.

cmp! tree w -- tree (as of 20.07)

Sets w as the compare function for the tree. Typically used after tree:parse .

data X -- x (as of 20.07)

Returns the data held in the node, not implemented for BTREE.


See also: tree:find tree:next tree:prev tree:parent
del tree x -- tree (as of 20.07)

Removes the node (if an X) or item (otherwise) from the tree. Not currently implemented for BK or BTREE trees.


See also: tree:find tree:next tree:prev tree:data tree:add
find tree x -- tree X (as of 20.07)

Does tree:search with a tolerance of 0, and returns the first matching node (not data item) which can be used to traverse the tree from that point.

Not implemented for BTREEs.


See also: tree:next tree:prev tree:data tree:parent
iter tree w n -- tree (as of 20.07)

Traverses the tree, invoking w for each node. The value of n (as per tree/enums library):

value meaning
1 pre-order (left,root,right)
2 in-order (root,left,right)
3 post-order (left,right,root)
4 rev-in-order (right,root,left)

The SED of w is x -- , where the item is the node's data. break stops the iteration.

next X -- X' (as of 20.07)

Gives the next node in the tree, or null . Not implemented for BK or BTREEs (returns null ).


See also: tree:find tree:prev tree:data tree:parent
nodes tree X -- tree a (as of 20.07)

Returns an array of the nodes which are children of the node.

parent X -- X' (as of 20.07)

Returns the node's parent, or null .


See also: tree:find tree:next tree:prev tree:data
parse s -- tree (as of 20.07)

Reconstitutes a tree from its string representation (from >s ).

prev X -- X' (as of 20.07)

Gives the previous node in the tree, or null . Not implemented for BK or BTREEs (returns null ).


See also: tree:find tree:next tree:data tree:parent
root tree -- tree X (as of 20.07)

Returns the root node of the tree, or null .


See also: tree:find tree:next tree:prev tree:data
search tree x n -- tree a (as of 20.07)

Searches the tree for items matching x within the (non-negative) tolerance n . Returns a possibly empty array of matches. A tolerance of zero means 'exact match'. For binary trees, tolerance means the number of surrounding items to return (tolerance not yet implemented for BTREEs).

trie w T -- tree (as of 21.05)

Creates a new TRIE. If T is true , the trie is case-insensitive; otherwise, it's case-sensitive. If the items to be inserted in the TRIE are strings, then w must be null ; otherwise, a word w must be provided to create a string representing the items inserted so that they can be ordered "lexicographically". Any UTF-8 string is acceptable as data.

If provided, the SED of w is x -- s .

websocket

Namespace: ws
Description: Web Socket utilities

word sed/description
close T -- b
needs net/websocket

Create a 'close' frame. T is true for the client, false for a server.

decode b -- m
needs net/websocket

Given a websocket packet in the buffer, return a map containing keys: "data" - the decoded data "op" - the websocket opcode "fin" - if 0, this is not the last packet of the message

encode x op fin -- b
needs net/websocket

Encode the buffer or string x with the opcode 'op' and final status 'fin'.

encode-nomask x op fin -- b
needs net/websocket

Encode the buffer or string x with the opcode 'op' and final status 'fin', but without masking; as appropriate for a server-to-client response.

gen-accept-header s -- s
needs net/websocket

Given the raw security key from the client, return an acceptance header

gen-accept-key s -- s
needs net/websocket

Convert the hashed 'Sec-Websocket-Key' we received into the expected response

opcodes -- n
needs net/websocket

Constants representing the opcodes for websocket packets: CONTINUATION, TEXT, BINARY, CLOSE, PING, PONG

open s -- net true | false
needs net/websocket-client

Try to open a websocket connection to the URL given. Returns 'true' followed by the net to use, or false if the connection was unable to be opened. A URL with 'ws://' or 'wss://' is accepted, as is 'http://' or 'https://'.

Word

Namespace: w
Description: Words are the smallest unit of execution

word sed/description
! x s -- (as of 17.06)

Stores the value x into the "local variable" named by the string. Before using this you must have invoked G:locals: !


See also: w:@ t:@ t:! G:locals:
(is) w s -- (as of 20.04)
IMMEDIATE

Same as w:is , but takes the name of the deferred word on TOS instead of parsing it.


See also: G:defer: G:(defer) w:is
@ s -- x | a -- x (as of 17.06)

Gets the "local variable" named by the string. The value x may be of any type, and if s is unknown then null is returned. If passed an array, all values corresponding to the passed in keys are returned.

Before using this word you must have invoked G:locals: !


See also: w:! t:@ t:! G:locals:
alias: w -- (as of 16.05)

Creates a new word named <name> and make it an alias for the word w . After this, invoking name will have the same effect as invoking w . May be used to give a name to an anonymous word, among other things.

cb w s -- X (as of 17.03)

Creates a new "callback" given a parameter specification string and a word which will be called-back by the FFI call. The parameter specification is in the same format as for G:func: .

You must use this if you need to pass a "callback function" to an FFI-invoked external function. If you do not, your callback will probably crash.

deprecate w -- (as of 17.03)

Marks the word as DEPRECATED. A word which is "deprecated" will print a warning message if it is invoked in interpret mode, or when it is compiled the first time into a new word. At runtime it will be silent; the warning is intended to alert the programmer that the word should be retired from use. The deprecation warning will appear only the first time the word is invoked or compiled.

Note: A deprecated word may be removed from 8th at any time after it was marked as such, so it is best to heed the warning message.

dlcall w -- x | w n -- x (as of 21.03)

Calls the dynamic-library function encapsulated in the word w which was returned by w:dlsym , using the FFI template string assigned then. Returns whatever the function would, if it does. If a number is on TOS, then that many parameters will be left on the stack after the FFI call. Most useful if the first parameter is something you want to retain after the call, but don't want to do stack twiddling.

dlopen s -- X | b -- X (as of 21.03)

Loads the dynamic library indicated by x from a path to the file to open.

Pro+: if given a buffer, it's a dynamic library in memory.

The returned item can be used with w:dlsym to return a word or other data item from the library. On failure, returns null .

dlsym X s nm s2 -- X w (as of 21.03)

Given an X returned by os:dlopen and a string representing an item to fetch from it, returns a word encapsulating the library entry named by nm . The string s2 is the FFI template to be used when invoking the word.

exec w --

Invoke (call, run, execute) the word. Does nothing if w is null .


See also: w:exec?
exec? s -- T

Try to invoke the word named by the string s , and return true if successful or false otherwise. If s is null returns false .


See also: w:exec
ffifail s -- (as of 18.06)
DEFFERED

Invoked if the FFI is unable to dynamically load the external function or library. The default behavior is to print a message and exit the app. s is a string which is the name of the "lib" or "func" which could not be loaded.

find s -- w

Look up the word named s and return the found word w , or null if it cannot be found.


See also: w:forget G:'
forget s -- | n --

Look up the word named by the string s , or the namespace designated by the number n , making it invisible to the w:find word. The word's code remains, but cannot be found or invoked by name.

If a namespace is "forgotten", it is also wiped so it is actually impossible to find words which were in the namespace. However, any references to such words will still be alive.


See also: w:find G:'
is w --
IMMEDIATE

Assign the word w as the action for the deferred word whose name is <name> , which was created using defer: . This assignment can be reversed using w:undo .


See also: G:defer:
name w -- w s (as of 19.09)

Returns the word's name.

undo w --

Undoes the last assignment from w:is to the deferred word.


See also: w:is G:defer:
xt w -- n (as of 24.06)
IMMEDIATE

Returns the "xt", or execution address/token of the given word.

xt> n -- w (as of 24.06)

Returns the word corresponding to an address, if possible; otherwise returns null .

XML

Namespace: xml
Description: XML parsing

word sed/description
>s x -- s
needs xml/parse

Convert the xml x to a string representation s. This will not necessarily be a complete round-trip of a file parsed with xml:parse.

>txt x -- x s
needs xml/parse

Given an xml x, return its text content, recursively, in a single string s.

md-init m -- X (as of 19.09)

Prepares to parse "Markdown text" using a push parser. The map requires all the following keys: "enter_span", "leave_span", "enter_block", "leave_block", "text". They must be words with a SED of m -- T , where T is true to stop processing, or false to continue.

The map the callback receives will contain the keys "text" and "user" if it's a "text" callback, or "tag" and "user" for all others.

See the libraries md/2html and md/2console for details on the callbacks; samples xml/md2html.8th and xml/md2console.8th for how to use the parser library. The manual has full documentation.

md-parse X x sb -- X T (as of 19.09)

Takes a parser created with xml:md-init , a user-provided value 'x', and a string or buffer containing Markdown text, and runs the parser invoking the callbacks defined in it. Returns true if the parse succeeded, or false and sets t:err? . The user-provided value is passed to the parser callbacks unmodified. The map received contains the key "tag", which describes the kind of item received. Depending on the tag type, other information is also conveyed. See the manual for more detailed information.

parse inp -- xml | xml null
needs xml/parse

Take an item (string or buffer or map) inp possibly containing XML and parse it into a map xml. Return null on TOS if it failed to parse (and "error" in the map returned under will explain why it failed). If inp is a map, then its contents will override the default parse and it must provide either a "inp" key with text, or a "read" key with appropriate behavior. Currently requires that the XML be encoded in UTF-8 (or compatible).

parse-html o -- x
needs xml/parse

Take an item (string or buffer) o containing HTML and parse it into a map, similar to xml:parse

parse-stream m -- (as of 18.04)

Parses a stream of XML according to the options in the given map, with word values whose keys are:

key description SED
/attr invoked when attribute ends s -- T
/elem invoked when element ends s -- T
attr invoked for each new XML element's attribute -- T
cont invoked when there is element content s -- T
done invoked on end of XML parse --
elem invoked for each new XML element s -- T
read returns a string or buffer to be parsed (required) -- s
val invoked for each new XML attribute's value s -- T

ZMQ

Namespace: zmq
Description: ZeroMQ interface

word sed/description
getmsg[] sock -- [buf]|null
needs net/zmq

Get multi-part messages as an array of buffers.

sendmsg[] sock arr --
needs net/zmq

Send (possibly) multi-part messages, given as an array of items to send.