Janet 1.27.0-01aab66 Documentation
(Other Versions: 1.26.0 1.25.1 1.24.0 1.23.0 1.22.0 1.21.0 1.20.0 1.19.0 1.18.1 1.17.1 1.16.1 1.15.0 1.13.1 1.12.2 1.11.1 1.10.1 1.9.1 1.8.1 1.7.0 1.6.0 1.5.1 1.5.0 1.4.0 1.3.1 )

Core API

Index

% %= * *= *args* *current-file* *debug* *defdyn-prefix* *doc-color* *doc-width* *err* *err-color* *executable* *exit* *exit-value* *ffi-context* *lint-error* *lint-levels* *lint-warn* *macro-form* *macro-lints* *out* *peg-grammar* *pretty-format* *profilepath* *redef* *syspath* + ++ += - -- -= -> ->> -?> -?>> / /= < <= = > >= abstract? accumulate accumulate2 all all-bindings all-dynamics and any? apply array array/clear array/concat array/ensure array/fill array/insert array/new array/new-filled array/peek array/pop array/push array/remove array/slice array/trim array? as-> as-macro as?-> asm assert bad-compile bad-parse band blshift bnot boolean? bor brshift brushift buffer buffer/bit buffer/bit-clear buffer/bit-set buffer/bit-toggle buffer/blit buffer/clear buffer/fill buffer/format buffer/new buffer/new-filled buffer/popn buffer/push buffer/push-at buffer/push-byte buffer/push-string buffer/push-word buffer/slice buffer/trim buffer? bxor bytes? cancel case cfunction? chr cli-main cmp comment comp compare compare< compare<= compare= compare> compare>= compif compile complement comptime compwhen cond coro count curenv debug debug/arg-stack debug/break debug/fbreak debug/lineage debug/stack debug/stacktrace debug/step debug/unbreak debug/unfbreak debugger debugger-env debugger-on-status dec deep-not= deep= def- default default-peg-grammar defdyn defer defglobal defmacro defmacro- defn defn- delay describe dictionary? disasm distinct doc doc* doc-format doc-of dofile drop drop-until drop-while dyn each eachk eachp edefer eflush empty? env-lookup eprin eprinf eprint eprintf error errorf ev/acquire-lock ev/acquire-rlock ev/acquire-wlock ev/call ev/cancel ev/capacity ev/chan ev/chan-close ev/chunk ev/close ev/count ev/deadline ev/do-thread ev/full ev/gather ev/give ev/give-supervisor ev/go ev/lock ev/read ev/release-lock ev/release-rlock ev/release-wlock ev/rselect ev/rwlock ev/select ev/sleep ev/spawn ev/spawn-thread ev/take ev/thread ev/thread-chan ev/with-deadline ev/write eval eval-string even? every? extreme false? ffi/align ffi/call ffi/close ffi/context ffi/defbind ffi/free ffi/jitfn ffi/lookup ffi/malloc ffi/native ffi/pointer-buffer ffi/read ffi/signature ffi/size ffi/struct ffi/trampoline ffi/write fiber-fn fiber/can-resume? fiber/current fiber/getenv fiber/last-value fiber/maxstack fiber/new fiber/root fiber/setenv fiber/setmaxstack fiber/status fiber? file/close file/flush file/open file/read file/seek file/tell file/temp file/write filter find find-index first flatten flatten-into flush flycheck for forever forv freeze frequencies from-pairs function? gccollect gcinterval gcsetinterval generate gensym get get-in getline getproto group-by hash idempotent? identity if-let if-not if-with import import* in inc index-of indexed? int/s64 int/to-bytes int/to-number int/u64 int? interleave interpose invert janet/build janet/config-bits janet/version juxt juxt* keep keys keyword keyword/slice keyword? kvs label last length let load-image load-image-dict loop macex macex1 maclintf make-env make-image make-image-dict map mapcat marshal match math/-inf math/abs math/acos math/acosh math/asin math/asinh math/atan math/atan2 math/atanh math/cbrt math/ceil math/cos math/cosh math/e math/erf math/erfc math/exp math/exp2 math/expm1 math/floor math/gamma math/gcd math/hypot math/inf math/int-max math/int-min math/int32-max math/int32-min math/lcm math/log math/log-gamma math/log10 math/log1p math/log2 math/nan math/next math/pi math/pow math/random math/rng math/rng-buffer math/rng-int math/rng-uniform math/round math/seedrandom math/sin math/sinh math/sqrt math/tan math/tanh math/trunc max max-of mean memcmp merge merge-into merge-module min min-of mod module/add-paths module/cache module/expand-path module/find module/loaders module/loading module/paths module/value nan? nat? native neg? net/accept net/accept-loop net/address net/address-unpack net/chunk net/close net/connect net/flush net/listen net/localname net/peername net/read net/recv-from net/send-to net/server net/shutdown net/write next nil? not not= number? odd? one? or os/arch os/cd os/chmod os/clock os/compiler os/cpu-count os/cryptorand os/cwd os/date os/dir os/environ os/execute os/exit os/getenv os/link os/lstat os/mkdir os/mktime os/open os/perm-int os/perm-string os/pipe os/proc-close os/proc-kill os/proc-wait os/readlink os/realpath os/rename os/rm os/rmdir os/setenv os/shell os/sleep os/spawn os/stat os/symlink os/time os/touch os/umask os/which pairs parse parse-all parser/byte parser/clone parser/consume parser/eof parser/error parser/flush parser/has-more parser/insert parser/new parser/produce parser/state parser/status parser/where partial partition partition-by peg/compile peg/find peg/find-all peg/match peg/replace peg/replace-all pos? postwalk pp prewalk prin prinf print printf product prompt propagate protect put put-in quit range reduce reduce2 repeat repl require resume return reverse reverse! root-env run-context sandbox scan-number seq setdyn short-fn signal slice slurp some sort sort-by sorted sorted-by spit stderr stdin stdout string string/ascii-lower string/ascii-upper string/bytes string/check-set string/find string/find-all string/format string/from-bytes string/has-prefix? string/has-suffix? string/join string/repeat string/replace string/replace-all string/reverse string/slice string/split string/trim string/triml string/trimr string? struct struct/getproto struct/proto-flatten struct/to-table struct/with-proto struct? sum symbol symbol/slice symbol? table table/clear table/clone table/getproto table/new table/proto-flatten table/rawget table/setproto table/to-struct table? tabseq take take-until take-while toggle trace tracev true? truthy? try tuple tuple/brackets tuple/setmap tuple/slice tuple/sourcemap tuple/type tuple? type unless unmarshal untrace update update-in use values var- varfn varglobal walk warn-compile when when-let when-with with with-dyns with-syms with-vars xprin xprinf xprint xprintf yield zero? zipcoll

function (% dividend divisor)
Returns the remainder of dividend / divisor.
Example:
(% 10 3) # -> 1
(% -10 3) # -> -1
(% 10 -3) # -> 1
(% -10 -3) # -> -1
(% 1.4 1) # -> 0.4
(% -1.4 1) # -> -0.4
(% 1.4 1) # -> 0.4
(% -1.4 1) # -> -0.4
(% -1.4 0) # -> -nan
(% -1.4 0) # -> -nan
Community Examples /
macro (%= x n)
Shorthand for (set x (% x n)).
Example:
(var x 10) # -> 10
(%= x 3) # -> 1
x # -> 1
Community Examples / source
function (* & xs)
Returns the product of all elements in xs. If xs is empty, returns 1.
Example:
(*) # -> 1
(* 10) # -> 10
(* 10 20) # -> 200
(* 1 2 3 4 5 6 7) #-> 5040

# Can take product of array with splice, but 'product' is better
(* ;(range 1 20)) #-> 1.21645e+17
(product (range 1 20)) #-> 1.21645e+17
Community Examples /
macro (*= x n)
Shorthand for (set x (\* x n)).
Example:
(var x 100) # -> 100
x # -> 100
(*= x 10) # -> 1000
x # -> 1000
Community Examples / source
keyword *args*
Dynamic bindings that will contain command line arguments at program start.
Community Examples / source
keyword *current-file*
Bound to the name of the currently compiling file.
Community Examples / source
keyword *debug*
Enables a built in debugger on errors and other useful features for debugging in a repl.
Community Examples / source
keyword *defdyn-prefix*
Optional namespace prefix to add to keywords declared with `defdyn`.
 Use this to prevent keyword collisions between dynamic bindings.
Community Examples / source
keyword *doc-color*
Whether or not to colorize documentation printed with `doc-format`.
Community Examples / source
keyword *doc-width*
Width in columns to print documentation printed with `doc-format`.
Community Examples / source
keyword *err*
Where error printing prints output to.
Community Examples / source
keyword *err-color*
Whether or not to turn on error coloring in stacktraces and other error messages.
Community Examples / source
keyword *executable*
Name of the interpreter executable used to execute this program. Corresponds to `argv[0]` in the call to
 `int main(int argc, char **argv);`.
Community Examples / source
keyword *exit*
When set, will cause the current context to complete. Can be set to exit from repl (or file), for example.
Community Examples / source
keyword *exit-value*
Set the return value from `run-context` upon an exit. By default, `run-context` will return nil.
Community Examples / source
keyword *ffi-context*
 Current native library for ffi/bind and other settings
Community Examples / source
keyword *lint-error*
The current lint error level. The error level is the lint level at which compilation will exit with an error and not continue.
Community Examples / source
keyword *lint-levels*
A table of keyword alias to numbers denoting a lint level. Can be used to provided custom aliases for numeric lint levels.
Community Examples / source
keyword *lint-warn*
The current lint warning level. The warning level is the lint level at which and error will be printed but compilation will continue as normal.
Community Examples / source
keyword *macro-form*
Inside a macro, is bound to the source form that invoked the macro
Community Examples / source
keyword *macro-lints*
Bound to an array of lint messages that will be reported by the compiler inside a macro.
To indicate an error or warning, a macro author should use `maclintf`.
Community Examples / source
keyword *out*
Where normal print functions print output to.
Community Examples / source
keyword *peg-grammar*
The implicit base grammar used when compiling PEGs. Any undefined keywords
found when compiling a peg will use lookup in this table (if defined).
Community Examples / source
keyword *pretty-format*
Format specifier for the `pp` function
Community Examples / source
keyword *profilepath*
Path to profile file loaded when starting up the repl.
Community Examples / source
keyword *redef*
When set, allow dynamically rebinding top level defs. Will slow generated code and is intended to be used for development.
Community Examples / source
keyword *syspath*
Path of directory to load system modules from.
Community Examples / source
function (+ & xs)
Returns the sum of all xs. xs must be integers or real numbers only. If xs is empty, return 0.
Example:
(+) # -> 0
(+ 10) # -> 10
(+ 1 2) # -> 3
(+ 1.4 -4.5) # -> -3.1
(+ 1 2 3 4 5 6 7 8 9 10) # -> 55

# Splice can be used to sum arrays, but 'sum' is better
(+ ;(range 101)) # -> 5050
(sum (range 101)) # -> 5050

# Janet can add types that support the :+ or :r+ method
(+ (int/s64 "10") 10) # -> <core/s64 20>

# Bad types give errors
(+ nil 10) # -> error: could not find method :+ for nil, or :r+ for 10
Community Examples /
macro (++ x)
Increments the var x by 1.
Community Examples / source
macro (+= x n)
Increments the var x by n.
Example:
(var x 100) # -> 100
x # -> 100
(+= x 10) # -> 110
x # -> 110
Community Examples / source
function (- & xs)
Returns the difference of xs. If xs is empty, returns 0. If xs has one element, returns the negative value of that element. Otherwise, returns the first element in xs minus the sum of the rest of the elements.
Example:
(-) # -> 0
(- 10) # -> -10
(- 1 2) # -> -1
(+ 1.4 -4.5) # -> 5.9

# Equivalent to (- first (+ ;rest))
(- 1 2 3 4 5 6 7 8 9 10) # -> -53

# Janet can subtract types that support the :- or :r- method
(- (int/s64 "10") 10) # -> <core/s64 0>
Community Examples /
macro (-- x)
Decrements the var x by 1.
Community Examples / source
macro (-= x n)
Decrements the var x by n.
Example:
(var x 10) # -> 10
(-= x 20) # -> -10
x # -> -10
Community Examples / source
macro (-> x & forms)
Threading macro. Inserts x as the second value in the first form
in `forms`, and inserts the modified first form into the second form
in the same manner, and so on. Useful for expressing pipelines of data.
Community Examples / source
macro (->> x & forms)
Threading macro. Inserts x as the last value in the first form
in `forms`, and inserts the modified first form into the second form
in the same manner, and so on. Useful for expressing pipelines of data.
Community Examples / source
macro (-?> x & forms)
Short circuit threading macro. Inserts x as the second value in the first form
in `forms`, and inserts the modified first form into the second form
in the same manner, and so on. The pipeline will return nil
if an intermediate value is nil.
Useful for expressing pipelines of data.
Community Examples / source
macro (-?>> x & forms)
Short circuit threading macro. Inserts x as the last value in the first form
in `forms`, and inserts the modified first form into the second form
in the same manner, and so on. The pipeline will return nil
if an intermediate value is nil.
Useful for expressing pipelines of data.
Community Examples / source
function ( )
(/ & xs)

Returns the quotient of xs. If xs is empty, returns 1. If xs has one value x, returns the reciprocal of x. Otherwise return the first value of xs repeatedly divided by the remaining values.
Community Examples /
macro ( )
(/= x n)

Shorthand for (set x (/ x n)).
Community Examples / source
function (< & xs)
Check if xs is in ascending order. Returns a boolean.
Community Examples /
function (<= & xs)
Check if xs is in non-descending order. Returns a boolean.
Community Examples /
function (= & xs)
Check if all values in xs are equal. Returns a boolean.
Community Examples /
function (> & xs)
Check if xs is in descending order. Returns a boolean.
Community Examples /
function (>= & xs)
Check if xs is in non-ascending order. Returns a boolean.
Community Examples /
cfunction (abstract? x)
Check if x is an abstract type.
Community Examples / source
function (accumulate f init ind)
Similar to `reduce`, but accumulates intermediate values into an array.
The last element in the array is what would be the return value from `reduce`.
The `init` value is not added to the array (the return value will have the same
number of elements as `ind`).
Returns a new array.
Community Examples / source
function (accumulate2 f ind)
The 2-argument version of `accumulate` that does not take an initialization value.
The first value in `ind` will be added to the array as is, so the length of the
return value will be `(length ind)`.
Community Examples / source
function (all pred xs)
Returns true if `(pred item)` returns a truthy value for every item in `xs`.
Otherwise, returns the first falsey `(pred item)` result encountered.
Returns true if `xs` is empty.
Community Examples / source
function (all-bindings &opt env local)
Get all symbols available in an environment. Defaults to the current
fiber's environment. If `local` is truthy, will not show inherited bindings
(from prototype tables).
Community Examples / source
function (all-dynamics &opt env local)
Get all dynamic bindings in an environment. Defaults to the current
fiber's environment. If `local` is truthy, will not show inherited bindings
(from prototype tables).
Community Examples / source
macro (and & forms)
Evaluates to the last argument if all preceding elements are truthy, otherwise
evaluates to the first falsey argument.
Community Examples / source
function (any? ind)
Returns the first truthy value in `ind`, otherwise nil.
Community Examples / source
function (apply f & args)
Applies a function to a variable number of arguments. Each element in args is used as an argument to f, except the last element in args, which is expected to be an array-like. Each element in this last argument is then also pushed as an argument to f. For example:

	(apply + 1000 (range 10))

sums the first 10 integers and 1000.
Example:
(apply + (range 10)) # -> 45
(apply + []) # -> 0
(apply + 1 2 3 4 5 6 7 [8 9 10]) # -> 55
(apply + 1 2 3 4 5 6 7 8 9 10) # -> error: expected array|tuple, got number 

# Can also be used to call macros like functions.
# Will return the macro expanded code of the original macro.
(apply for 'x 0 10 ['(print x)])
# -> (do (var _000000 0) (def _000001 10) (while ...
Community Examples /
cfunction (array & items)
Create a new array that contains items. Returns the new array.
Community Examples / source
cfunction (array/clear arr)
Empties an array, setting it's count to 0 but does not free the backing capacity. Returns the modified array.
Community Examples / source
cfunction (array/concat arr & parts)
Concatenates a variable number of arrays (and tuples) into the first argument, which must be an array. If any of the parts are arrays or tuples, their elements will be inserted into the array. Otherwise, each part in `parts` will be appended to `arr` in order. Return the modified array `arr`.
Community Examples / source
cfunction (array/ensure arr capacity growth)
Ensures that the memory backing the array is large enough for `capacity` items at the given rate of growth. `capacity` and `growth` must be integers. If the backing capacity is already enough, then this function does nothing. Otherwise, the backing memory will be reallocated so that there is enough space.
Community Examples / source
cfunction (array/fill arr &opt value)
Replace all elements of an array with `value` (defaulting to nil) without changing the length of the array. Returns the modified array.
Community Examples / source
cfunction (array/insert arr at & xs)
Insert all `xs` into array `arr` at index `at`. `at` should be an integer between 0 and the length of the array. A negative value for `at` will index backwards from the end of the array, such that inserting at -1 appends to the array. Returns the array.
Community Examples / source
cfunction (array/new capacity)
Creates a new empty array with a pre-allocated capacity. The same as `(array)` but can be more efficient if the maximum size of an array is known.
Example:
(def arr (array/new 100)) # -> @[]

# Now we can fill up the array without triggering a resize
(for i 0 100
  (put arr i i))
Community Examples / source
cfunction (array/new-filled count &opt value)
Creates a new array of `count` elements, all set to `value`, which defaults to nil. Returns the new array.
Community Examples / source
cfunction (array/peek arr)
Returns the last element of the array. Does not modify the array.
Community Examples / source
cfunction (array/pop arr)
Remove the last element of the array and return it. If the array is empty, will return nil. Modifies the input array.
Community Examples / source
cfunction (array/push arr x)
Insert an element in the end of an array. Modifies the input array and returns it.
Community Examples / source
cfunction (array/remove arr at &opt n)
Remove up to `n` elements starting at index `at` in array `arr`. `at` can index from the end of the array with a negative index, and `n` must be a non-negative integer. By default, `n` is 1. Returns the array.
Community Examples / source
cfunction (array/slice arrtup &opt start end)
Takes a slice of array or tuple from `start` to `end`. The range is half open, [start, end). Indexes can also be negative, indicating indexing from the end of the array. By default, `start` is 0 and `end` is the length of the array. Note that index -1 is synonymous with index `(length arrtup)` to allow a full negative slice range. Returns a new array.
Community Examples / source
cfunction (array/trim arr)
Set the backing capacity of an array to its current length. Returns the modified array.
Community Examples / source
function (array? x)
Check if x is an array.
Community Examples / source
macro (as-> x as & forms)
Thread forms together, replacing `as` in `forms` with the value
of the previous form. The first form is the value x. Returns the
last value.
Community Examples / source
macro (as-macro f & args)
Use a function or macro literal `f` as a macro. This lets
any function be used as a macro. Inside a quasiquote, the
idiom `(as-macro ,my-custom-macro arg1 arg2...)` can be used
to avoid unwanted variable capture of `my-custom-macro`.
Community Examples / source
macro (as?-> x as & forms)
Thread forms together, replacing `as` in `forms` with the value
of the previous form. The first form is the value x. If any
intermediate values are falsey, return nil; otherwise, returns the
last value.
Community Examples / source
cfunction (asm assembly)
Returns a new function that is the compiled result of the assembly.
The syntax for the assembly can be found on the Janet website, and should correspond
to the return value of disasm. Will throw an
error on invalid assembly.
Community Examples / source
macro (assert x &opt err)
Throw an error if x is not truthy. Will not evaluate `err` if x is truthy.
Community Examples / source
function (bad-compile msg macrof where &opt line col)
Default handler for a compile error.
Community Examples / source
function (bad-parse p where)
Default handler for a parse error.
Community Examples / source
function (band & xs)
Returns the bit-wise and of all values in xs. Each x in xs must be an integer.
Community Examples /
function (blshift x & shifts)
Returns the value of x bit shifted left by the sum of all values in shifts. x and each element in shift must be an integer.
Community Examples /
function (bnot x)
Returns the bit-wise inverse of integer x.
Community Examples /
function (boolean? x)
Check if x is a boolean.
Community Examples / source
function (bor & xs)
Returns the bit-wise or of all values in xs. Each x in xs must be an integer.
Community Examples /
function (brshift x & shifts)
Returns the value of x bit shifted right by the sum of all values in shifts. x and each element in shift must be an integer.
Community Examples /
function (brushift x & shifts)
Returns the value of x bit shifted right by the sum of all values in shifts. x and each element in shift must be an integer. The sign of x is not preserved, so for positive shifts the return value will always be positive.
Community Examples /
cfunction (buffer & xs)
Creates a buffer by concatenating the elements of `xs` together. If an element is not a byte sequence, it is converted to bytes via `describe`. Returns the new buffer.
Community Examples / source
cfunction (buffer/bit buffer index)
Gets the bit at the given bit-index. Returns true if the bit is set, false if not.
Community Examples / source
cfunction (buffer/bit-clear buffer index)
Clears the bit at the given bit-index. Returns the buffer.
Community Examples / source
cfunction (buffer/bit-set buffer index)
Sets the bit at the given bit-index. Returns the buffer.
Community Examples / source
cfunction (buffer/bit-toggle buffer index)
Toggles the bit at the given bit index in buffer. Returns the buffer.
Community Examples / source
cfunction (buffer/blit dest src &opt dest-start src-start src-end)
Insert the contents of `src` into `dest`. Can optionally take indices that indicate which part of `src` to copy into which part of `dest`. Indices can be negative in order to index from the end of `src` or `dest`. Returns `dest`.
Community Examples / source
cfunction (buffer/clear buffer)
Sets the size of a buffer to 0 and empties it. The buffer retains its memory so it can be efficiently refilled. Returns the modified buffer.
Community Examples / source
cfunction (buffer/fill buffer &opt byte)
Fill up a buffer with bytes, defaulting to 0s. Does not change the buffer's length. Returns the modified buffer.
Community Examples / source
cfunction (buffer/format buffer format & args)
Snprintf like functionality for printing values into a buffer. Returns the modified buffer.
Community Examples / source
cfunction (buffer/new capacity)
Creates a new, empty buffer with enough backing memory for `capacity` bytes. Returns a new buffer of length 0.
Community Examples / source
cfunction (buffer/new-filled count &opt byte)
Creates a new buffer of length `count` filled with `byte`. By default, `byte` is 0. Returns the new buffer.
Community Examples / source
cfunction (buffer/popn buffer n)
Removes the last `n` bytes from the buffer. Returns the modified buffer.
Community Examples / source
cfunction (buffer/push buffer & xs)
Push both individual bytes and byte sequences to a buffer. For each x in xs, push the byte if x is an integer, otherwise push the bytesequence to the buffer. Thus, this function behaves like both `buffer/push-string` and `buffer/push-byte`. Returns the modified buffer. Will throw an error if the buffer overflows.
Community Examples / source
cfunction (buffer/push-at buffer index & xs)
Same as buffer/push, but inserts new data at index `index`.
Community Examples / source
cfunction (buffer/push-byte buffer & xs)
Append bytes to a buffer. Will expand the buffer as necessary. Returns the modified buffer. Will throw an error if the buffer overflows.
Community Examples / source
cfunction (buffer/push-string buffer & xs)
Push byte sequences onto the end of a buffer. Will accept any of strings, keywords, symbols, and buffers. Returns the modified buffer. Will throw an error if the buffer overflows.
Community Examples / source
cfunction (buffer/push-word buffer & xs)
Append machine words to a buffer. The 4 bytes of the integer are appended in twos complement, little endian order, unsigned for all x. Returns the modified buffer. Will throw an error if the buffer overflows.
Community Examples / source
cfunction (buffer/slice bytes &opt start end)
Takes a slice of a byte sequence from `start` to `end`. The range is half open, [start, end). Indexes can also be negative, indicating indexing from the end of the end of the array. By default, `start` is 0 and `end` is the length of the buffer. Returns a new buffer.
Community Examples / source
cfunction (buffer/trim buffer)
Set the backing capacity of the buffer to the current length of the buffer. Returns the modified buffer.
Community Examples / source
function (buffer? x)
Check if x is a buffer.
Community Examples / source
function (bxor & xs)
Returns the bit-wise xor of all values in xs. Each in xs must be an integer.
Community Examples /
function (bytes? x)
Check if x is a string, symbol, keyword, or buffer.
Community Examples / source
function (cancel fiber err)
Resume a fiber but have it immediately raise an error. This lets a programmer unwind a pending fiber. Returns the same result as resume.
Community Examples /
macro (case dispatch & pairs)
Select the body that equals the dispatch value. When `pairs`
has an odd number of elements, the last is the default expression.
If no match is found, returns nil.
Community Examples / source
function (cfunction? x)
Check if x a cfunction.
Community Examples / source
macro (chr c)
Convert a string of length 1 to its byte (ascii) value at compile time.
Community Examples / source
function (cli-main args)
Entrance for the Janet CLI tool. Call this function with the command line
arguments as an array or tuple of strings to invoke the CLI interface.
Community Examples / source
function (cmp x y)
Returns -1 if x is strictly less than y, 1 if y is strictly greater than x, and 0 otherwise. To return 0, x and y must be the exact same type.
Community Examples /
macro (comment &)
Ignores the body of the comment.
Community Examples / source
function (comp & functions)
Takes multiple functions and returns a function that is the composition
of those functions.
Community Examples / source
function (compare x y)
Polymorphic compare. Returns -1, 0, 1 for x < y, x = y, x > y respectively.
Differs from the primitive comparators in that it first checks to
see whether either x or y implement a `compare` method which can
compare x and y. If so, it uses that method. If not, it
delegates to the primitive comparators.
Community Examples / source
function (compare< & xs)
Equivalent of `<` but using polymorphic `compare` instead of primitive comparator.
Community Examples / source
function (compare<= & xs)
Equivalent of `<=` but using polymorphic `compare` instead of primitive comparator.
Community Examples / source
function (compare= & xs)
Equivalent of `=` but using polymorphic `compare` instead of primitive comparator.
Community Examples / source
function (compare> & xs)
Equivalent of `>` but using polymorphic `compare` instead of primitive comparator.
Community Examples / source
function (compare>= & xs)
Equivalent of `>=` but using polymorphic `compare` instead of primitive comparator.
Community Examples / source
macro (compif cnd tru &opt fals)
Check the condition `cnd` at compile time -- if truthy, compile `tru`, else compile `fals`.
Community Examples / source
cfunction (compile ast &opt env source lints)
Compiles an Abstract Syntax Tree (ast) into a function. Pair the compile function with parsing functionality to implement eval. Returns a new function and does not modify ast. Returns an error struct with keys :line, :column, and :error if compilation fails. If a `lints` array is given, linting messages will be appended to the array. Each message will be a tuple of the form `(level line col message)`.
Community Examples / source
function (complement f)
Returns a function that is the complement to the argument.
Community Examples / source
macro (comptime x)
Evals x at compile time and returns the result. Similar to a top level unquote.
Community Examples / source
macro (compwhen cnd & body)
Check the condition `cnd` at compile time -- if truthy, compile `(upscope ;body)`, else compile nil.
Community Examples / source
macro (cond & pairs)
Evaluates conditions sequentially until the first true condition
is found, and then executes the corresponding body. If there are an
odd number of forms, and no forms are matched, the last expression
is executed. If there are no matches, returns nil.
Community Examples / source
macro (coro & body)
A wrapper for making fibers that may yield multiple values (coroutine). Same as `(fiber/new (fn [] ;body) :yi)`.
Community Examples / source
function (count pred ind)
Count the number of items in `ind` for which `(pred item)`
is true.
Community Examples / source
function (curenv &opt n)
Get the current environment table. Same as `(fiber/getenv (fiber/current))`. If `n`
is provided, gets the nth prototype of the environment table.
Community Examples / source
function (debug &opt x)
Throws a debug signal that can be caught by a parent fiber and used to inspect the running state of the current fiber. Returns the value passed in by resume.
Community Examples /
cfunction (debug/arg-stack fiber)
Gets all values currently on the fiber's argument stack. Normally, this should be empty unless the fiber signals while pushing arguments to make a function call. Returns a new array.
Community Examples / source
cfunction (debug/break source line col)
Sets a breakpoint in `source` at a given line and column. Will throw an error if the breakpoint location cannot be found. For example

	(debug/break "core.janet" 10 4)

will set a breakpoint at line 10, 4th column of the file core.janet.
Community Examples / source
cfunction (debug/fbreak fun &opt pc)
Set a breakpoint in a given function. pc is an optional offset, which is in bytecode instructions. fun is a function value. Will throw an error if the offset is too large or negative.
Community Examples / source
cfunction (debug/lineage fib)
Returns an array of all child fibers from a root fiber. This function is useful when a fiber signals or errors to an ancestor fiber. Using this function, the fiber handling the error can see which fiber raised the signal. This function should be used mostly for debugging purposes.
Community Examples / source
cfunction (debug/stack fib)
Gets information about the stack as an array of tables. Each table in the array contains information about a stack frame. The top-most, current stack frame is the first table in the array, and the bottom-most stack frame is the last value. Each stack frame contains some of the following attributes:

* :c - true if the stack frame is a c function invocation

* :source-column - the current source column of the stack frame

* :function - the function that the stack frame represents

* :source-line - the current source line of the stack frame

* :name - the human-friendly name of the function

* :pc - integer indicating the location of the program counter

* :source - string with the file path or other identifier for the source code

* :slots - array of all values in each slot

* :tail - boolean indicating a tail call
Community Examples / source
cfunction (debug/stacktrace fiber &opt err prefix)
Prints a nice looking stacktrace for a fiber. Can optionally provide an error value to print the stack trace with. If `err` is nil or not provided, and no prefix is given, will skip the error line. Returns the fiber.
Community Examples / source
cfunction (debug/step fiber &opt x)
Run a fiber for one virtual instruction of the Janet machine. Can optionally pass in a value that will be passed as the resuming value. Returns the signal value, which will usually be nil, as breakpoints raise nil signals.
Community Examples / source
cfunction (debug/unbreak source line column)
Remove a breakpoint with a source key at a given line and column. Will throw an error if the breakpoint cannot be found.
Community Examples / source
cfunction (debug/unfbreak fun &opt pc)
Unset a breakpoint set with debug/fbreak.
Community Examples / source
function (debugger fiber &opt level)
Run a repl-based debugger on a fiber. Optionally pass in a level to differentiate nested debuggers.
Community Examples / source
table debugger-env
An environment that contains dot prefixed functions for debugging.
Community Examples / source
function (debugger-on-status env &opt level is-repl)
Create a function that can be passed to `run-context`'s `:on-status` argument that will drop into a debugger on errors. The debugger will only start on abnormal signals if the env table has the `:debug` dyn set to a truthy value.
Community Examples / source
function (dec x)
Returns x - 1.
Community Examples / source
function (deep-not= x y)
Like `not=`, but mutable types (arrays, tables, buffers) are considered
equal if they have identical structure. Much slower than `not=`.
Community Examples / source
function (deep= x y)
Like `=`, but mutable types (arrays, tables, buffers) are considered
equal if they have identical structure. Much slower than `=`.
Community Examples / source
macro (def- name & more)
Define a private value that will not be exported.
Example:
# In a file module.janet
(def- private-thing :encapsulated)
(def public-thing :exposed)

# In a file main.janet
(import module)

module/private-thing # -> Unknown symbol
module/public-thing # -> :exposed

# Same as normal def with :private metadata
(def :private x private-thing :encapsulated)
Community Examples / source
macro (default sym val)
Define a default value for an optional argument.
Expands to `(def sym (if (= nil sym) val sym))`.
Community Examples / source
table default-peg-grammar
The default grammar used for pegs. This grammar defines several common patterns
that should make it easier to write more complex patterns.
Community Examples / source
macro (defdyn alias & more)
Define an alias for a keyword that is used as a dynamic binding. The
alias is a normal, lexically scoped binding that can be used instead of
a keyword to prevent typos. `defdyn` does not set dynamic bindings or otherwise
replace `dyn` and `setdyn`. The alias _must_ start and end with the `*` character, usually
called "earmuffs".
Community Examples / source
macro (defer form & body)
Run `form` unconditionally after `body`, even if the body throws an error.
Will also run `form` if a user signal 0-4 is received.
Example:
# Evaluates to 6 after printing "scope left!"
(defer (print "scope left!")
  (+ 1 2 3))

# cleanup will always be called, even if there is a failure
(defer (cleanup)
  (step-1)
  (step-2)
  (if (< 0.1 (math/random)) (error "failure"))
  (step-3))
Community Examples / source
function (defglobal name value)
Dynamically create a global def.
Community Examples / source
macro (defmacro name & more)
Define a macro.
Community Examples / source
macro (defmacro- name & more)
Define a private macro that will not be exported.
Community Examples / source
macro (defn name & more)
Define a function. Equivalent to `(def name (fn name [args] ...))`.
Example:
(defn simple
  [x]
  (print (+ x 1)))

(simple 10) # -> 11

(defn long-body
  [y]
  (print y)
  (print (+ y 1))
  (print (+ y 2))
  (+ y 3))

(defn with-docstring
  "This function has a docstring"
  []
  (print "hello!"))

(defn with-tags
  :tag1 :tag2 :private
  "Also has a docstring and a variadic argument 'more'!"
  [x y z & more]
  [x y z more])

(with-tags 1 2) # raises arity error
(with-tags 1 2 3) # -> (1 2 3 ())
(with-tags 1 2 3 4) # -> (1 2 3 (4))
(with-tags 1 2 3 4 5) # -> (1 2 3 (4 5))

# Tags (and other metadata) are (usually) visible in the environment.
(dyn 'with-tags) # -> @{:tag2 true :value <function with-tags> :doc "(with-tags x y z & more)\n\nAlso has a docstring..." :source-map ("repl" 4 1) :tag1 true :private true}

Community Examples / source
macro (defn- name & more)
Define a private function that will not be exported.
Example:
# In a file module.janet
(defn- not-exposed-fn
  [x]
  (+ x x))
(not-exposed-fn 10) # -> 20

# In a file main.janet
(import module)

(module/not-exposed-fn 10) # -> Unknown symbol error

# Same as
(defn not-exposed-fn
  :private
  [x]
  (+ x x))
Community Examples / source
macro (delay & forms)
Lazily evaluate a series of expressions. Returns a function that returns the result of the last expression. Will only evaluate the body once, and then memoizes the result.
Community Examples / source
cfunction (describe x)
Returns a string that is a human-readable description of `x`. For recursive data structures, the string returned contains a pointer value from which the identity of `x` can be determined.
Community Examples / source
function (dictionary? x)
Check if x is a table or struct.
Community Examples / source
cfunction (disasm func &opt field)
Returns assembly that could be used to compile the given function. func must be a function, not a c function. Will throw on error on a badly typed argument. If given a field name, will only return that part of the function assembly. Possible fields are:

* :arity - number of required and optional arguments.
* :min-arity - minimum number of arguments function can be called with.
* :max-arity - maximum number of arguments function can be called with.
* :vararg - true if function can take a variable number of arguments.
* :bytecode - array of parsed bytecode instructions. Each instruction is a tuple.
* :source - name of source file that this function was compiled from.
* :name - name of function.
* :slotcount - how many virtual registers, or slots, this function uses. Corresponds to stack space used by function.
* :symbolmap - all symbols and their slots.
* :constants - an array of constants referenced by this function.
* :sourcemap - a mapping of each bytecode instruction to a line and column in the source file.
* :environments - an internal mapping of which enclosing functions are referenced for bindings.
* :defs - other function definitions that this function may instantiate.
Community Examples / source
function (distinct xs)
Returns an array of the deduplicated values in `xs`.
Community Examples / source
macro (doc &opt sym)
Shows documentation for the given symbol, or can show a list of available bindings.
If `sym` is a symbol, will look for documentation for that symbol. If `sym` is a string
or is not provided, will show all lexical and dynamic bindings in the current environment
containing that string (all bindings will be shown if no string is given).
Community Examples / source
function (doc* &opt sym)
Get the documentation for a symbol in a given environment. Function form of `doc`.
Community Examples / source
function (doc-format str &opt width indent colorize)
Reformat a docstring to wrap a certain width. Docstrings can either be plaintext
or a subset of markdown. This allows a long single line of prose or formatted text to be
a well-formed docstring. Returns a buffer containing the formatted text.
Community Examples / source
function (doc-of x)
Searches all loaded modules in module/cache for a given binding and prints out its documentation.
This does a search by value instead of by name. Returns nil.
Community Examples / source
function (dofile path &named exit env source expander evaluator read parser)
Evaluate a file, file path, or stream and return the resulting environment. :env, :expander,
:source, :evaluator, :read, and :parser are passed through to the underlying
`run-context` call. If `exit` is true, any top level errors will trigger a
call to `(os/exit 1)` after printing the error.
Community Examples / source
function (drop n ind)
Drop the first n elements in an indexed or bytes type. Returns a new tuple or string
instance, respectively.
Community Examples / source
function (drop-until pred ind)
Same as `(drop-while (complement pred) ind)`.
Community Examples / source
function (drop-while pred ind)
Given a predicate, remove elements from an indexed or bytes type that satisfy
the predicate, and abort on first failure. Returns a new tuple or string, respectively.
Community Examples / source
cfunction (dyn key &opt default)
Get a dynamic binding. Returns the default value (or nil) if no binding found.
Community Examples / source
macro (each x ds & body)
Loop over each value in `ds`. Returns nil.
Community Examples / source
macro (eachk x ds & body)
Loop over each key in `ds`. Returns nil.
Community Examples / source
macro (eachp x ds & body)
Loop over each (key, value) pair in `ds`. Returns nil.
Community Examples / source
macro (edefer form & body)
Run `form` after `body` in the case that body terminates abnormally (an error or user signal 0-4).
Otherwise, return last form in `body`.
Example:
# Half of the time, return "ok", the other
# half of the time, print there was an error and throw "oops".
(edefer (print "there was an error")
  (if (< (math/random) 0.5)
    (error "oops")
    "ok"))
Community Examples / source
cfunction (eflush )
Flush `(dyn :err stderr)` if it is a file, otherwise do nothing.
Community Examples / source
function (empty? xs)
Check if xs is empty.
Community Examples / source
cfunction (env-lookup env)
Creates a forward lookup table for unmarshalling from an environment. To create a reverse lookup table, use the invert function to swap keys and values in the returned table.
Community Examples / source
cfunction (eprin & xs)
Same as `prin`, but uses `(dyn :err stderr)` instead of `(dyn :out stdout)`.
Community Examples / source
cfunction (eprinf fmt & xs)
Like `eprintf` but with no trailing newline.
Community Examples / source
cfunction (eprint & xs)
Same as `print`, but uses `(dyn :err stderr)` instead of `(dyn :out stdout)`.
Community Examples / source
cfunction (eprintf fmt & xs)
Prints output formatted as if with `(string/format fmt ;xs)` to `(dyn :err stderr)` with a trailing newline.
Community Examples / source
function (error e)
Throws an error e that can be caught and handled by a parent fiber.
Community Examples /
function (errorf fmt & args)
A combination of `error` and `string/format`. Equivalent to `(error (string/format fmt ;args))`.
Community Examples / source
cfunction (ev/acquire-lock lock)
Acquire a lock such that this operating system thread is the only thread with access to this resource. This will block this entire thread until the lock becomes available, and will not yield to other fibers on this system thread.
Community Examples / source
cfunction (ev/acquire-rlock rwlock)
Acquire a read lock an a read-write lock.
Community Examples / source
cfunction (ev/acquire-wlock rwlock)
Acquire a write lock on a read-write lock.
Community Examples / source
function (ev/call f & args)
Call a function asynchronously.
Returns a fiber that is scheduled to run the function.
Community Examples / source
cfunction (ev/cancel fiber err)
Cancel a suspended fiber in the event loop. Differs from cancel in that it returns the canceled fiber immediately.
Community Examples / source
cfunction (ev/capacity channel)
Get the number of items a channel will store before blocking writers.
Community Examples / source
cfunction (ev/chan &opt capacity)
Create a new channel. capacity is the number of values to queue before blocking writers, defaults to 0 if not provided. Returns a new channel.
Community Examples / source
cfunction (ev/chan-close chan)
Close a channel. A closed channel will cause all pending reads and writes to return nil. Returns the channel.
Community Examples / source
cfunction (ev/chunk stream n &opt buffer timeout)
Same as ev/read, but will not return early if less than n bytes are available. If an end of stream is reached, will also return early with the collected bytes.
Community Examples / source
cfunction (ev/close stream)
Close a stream. This should be the same as calling (:close stream) for all streams.
Community Examples / source
cfunction (ev/count channel)
Get the number of items currently waiting in a channel.
Community Examples / source
cfunction (ev/deadline sec &opt tocancel tocheck)
Set a deadline for a fiber `tocheck`. If `tocheck` is not finished after `sec` seconds, `tocancel` will be canceled as with `ev/cancel`. If `tocancel` and `tocheck` are not given, they default to `(fiber/root)` and `(fiber/current)` respectively. Returns `tocancel`.
Community Examples / source
macro (ev/do-thread & body)
Run some code in a new thread. Suspends the current fiber until the thread is complete, and
evaluates to nil.
Community Examples / source
cfunction (ev/full channel)
Check if a channel is full or not.
Community Examples / source
macro (ev/gather & bodies)
Run a number of fibers in parallel on the event loop, and join when they complete.
Returns the gathered results in an array.
Community Examples / source
cfunction (ev/give channel value)
Write a value to a channel, suspending the current fiber if the channel is full. Returns the channel if the write succeeded, nil otherwise.
Community Examples / source
cfunction (ev/give-supervisor tag & payload)
Send a message to the current supervisor channel if there is one. The message will be a tuple of all of the arguments combined into a single message, where the first element is tag. By convention, tag should be a keyword indicating the type of message. Returns nil.
Community Examples / source
cfunction (ev/go fiber-or-fun &opt value supervisor)
Put a fiber on the event loop to be resumed later. If a function is used, it is wrapped with `fiber/new` first. Optionally pass a value to resume with, otherwise resumes with nil. Returns the fiber. An optional `core/channel` can be provided as a supervisor. When various events occur in the newly scheduled fiber, an event will be pushed to the supervisor. If not provided, the new fiber will inherit the current supervisor.
Community Examples / source
cfunction (ev/lock )
Create a new lock to coordinate threads.
Community Examples / source
cfunction (ev/read stream n &opt buffer timeout)
Read up to n bytes into a buffer asynchronously from a stream. `n` can also be the keyword `:all` to read into the buffer until end of stream. Optionally provide a buffer to write into as well as a timeout in seconds after which to cancel the operation and raise an error. Returns the buffer if the read was successful or nil if end-of-stream reached. Will raise an error if there are problems with the IO operation.
Community Examples / source
cfunction (ev/release-lock lock)
Release a lock such that other threads may acquire it.
Community Examples / source
cfunction (ev/release-rlock rwlock)
Release a read lock on a read-write lock
Community Examples / source
cfunction (ev/release-wlock rwlock)
Release a write lock on a read-write lock
Community Examples / source
cfunction (ev/rselect & clauses)
Similar to ev/select, but will try clauses in a random order for fairness.
Community Examples / source
cfunction (ev/rwlock )
Create a new read-write lock to coordinate threads.
Community Examples / source
cfunction (ev/select & clauses)
Block until the first of several channel operations occur. Returns a tuple of the form [:give chan], [:take chan x], or [:close chan], where a :give tuple is the result of a write and :take tuple is the result of a read. Each clause must be either a channel (for a channel take operation) or a tuple [channel x] for a channel give operation. Operations are tried in order, such that the first clauses will take precedence over later clauses. Both and give and take operations can return a [:close chan] tuple, which indicates that the specified channel was closed while waiting, or that the channel was already closed.
Community Examples / source
cfunction (ev/sleep sec)
Suspend the current fiber for sec seconds without blocking the event loop.
Community Examples / source
macro (ev/spawn & body)
Run some code in a new fiber. This is shorthand for `(ev/go (fn [] ;body))`.
Community Examples / source
macro (ev/spawn-thread & body)
Run some code in a new thread. Like `ev/do-thread`, but returns nil immediately.
Community Examples / source
cfunction (ev/take channel)
Read from a channel, suspending the current fiber if no value is available.
Community Examples / source
cfunction (ev/thread main &opt value flags supervisor)
Run `main` in a new operating system thread, optionally passing `value` to resume with. The parameter `main` can either be a fiber, or a function that accepts 0 or 1 arguments. Unlike `ev/go`, this function will suspend the current fiber until the thread is complete. If you want to run the thread without waiting for a result, pass the `:n` flag to return nil immediately. Otherwise, returns nil. Available flags:

* `:n` - return immediately
* `:t` - set the task-id of the new thread to value. The task-id is passed in messages to the supervisor channel.
* `:a` - don't copy abstract registry to new thread (performance optimization)
* `:c` - don't copy cfunction registry to new thread (performance optimization)
Community Examples / source
cfunction (ev/thread-chan &opt limit)
Create a threaded channel. A threaded channel is a channel that can be shared between threads and used to communicate between any number of operating system threads.
Community Examples / source
macro (ev/with-deadline deadline & body)
Run a body of code with a deadline, such that if the code does not complete before
the deadline is up, it will be canceled.
Community Examples / source
cfunction (ev/write stream data &opt timeout)
Write data to a stream, suspending the current fiber until the write completes. Takes an optional timeout in seconds, after which will return nil. Returns nil, or raises an error if the write failed.
Community Examples / source
function (eval form)
Evaluates a form in the current environment. If more control over the
environment is needed, use `run-context`.
Example:
(eval '(+ 1 2 3)) # -> 6
(eval '(error :oops)) # -> raises error :oops
(eval '(+ nil nil)) # -> raises error
Community Examples / source
function (eval-string str)
Evaluates a string in the current environment. If more control over the
environment is needed, use `run-context`.
Example:
(eval-string "(+ 1 2 3 4)") # -> 10
(eval-string ")") # -> parse error
(eval-string "(bloop)") # -> compile error
(eval-string "(+ nil nil)") # -> runtime error
Community Examples / source
function (even? x)
Check if x is even.
Community Examples / source
function (every? ind)
Returns true if each value in `ind` is truthy, otherwise returns the first
falsey value.
Community Examples / source
function (extreme order args)
Returns the most extreme value in `args` based on the function `order`.
`order` should take two values and return true or false (a comparison).
Returns nil if `args` is empty.
Community Examples / source
function (false? x)
Check if x is false.
Community Examples / source
cfunction (ffi/align type)
Get the align of an ffi type in bytes.
Community Examples / source
cfunction (ffi/call pointer signature & args)
Call a raw pointer as a function pointer. The function signature specifies how Janet values in `args` are converted to native machine types.
Community Examples / source
cfunction (ffi/close native)
Free a native object. Dereferencing pointers to symbols in the object will have undefined behavior after freeing.
Community Examples / source
function (ffi/context &opt native-path &named map-symbols lazy)
Set the path of the dynamic library to implictly bind, as well as other global state for ease of creating native bindings.
Community Examples / source
macro (ffi/defbind name ret-type & body)
Generate bindings for native functions in a convenient manner.
Community Examples / source
cfunction (ffi/free pointer)
Free memory allocated with `ffi/malloc`. Returns nil.
Community Examples / source
cfunction (ffi/jitfn bytes)
Create an abstract type that can be used as the pointer argument to `ffi/call`. The content of `bytes` is architecture specific machine code that will be copied into executable memory.
Community Examples / source
cfunction (ffi/lookup native symbol-name)
Lookup a symbol from a native object. All symbol lookups will return a raw pointer if the symbol is found, else nil.
Community Examples / source
cfunction (ffi/malloc size)
Allocates memory directly using the janet memory allocator. Memory allocated in this way must be freed manually! Returns a raw pointer, or nil if size = 0.
Community Examples / source
cfunction (ffi/native &opt path)
Load a shared object or dll from the given path, and do not extract or run any code from it. This is different than `native`, which will run initialization code to get a module table. If `path` is nil, opens the current running binary. Returns a `core/native`.
Community Examples / source
cfunction (ffi/pointer-buffer pointer capacity &opt count offset)
Create a buffer from a pointer. The underlying memory of the buffer will not be reallocated or freed by the garbage collector, allowing unmanaged, mutable memory to be manipulated with buffer functions. Attempts to resize or extend the buffer beyond its initial capacity will raise an error. As with many FFI functions, this is memory unsafe and can potentially allow out of bounds memory access. Returns a new buffer.
Community Examples / source
cfunction (ffi/read ffi-type bytes &opt offset)
Parse a native struct out of a buffer and convert it to normal Janet data structures. This function is the inverse of `ffi/write`. `bytes` can also be a raw pointer, although this is unsafe.
Community Examples / source
cfunction (ffi/signature calling-convention ret-type & arg-types)
Create a function signature object that can be used to make calls with raw function pointers.
Community Examples / source
cfunction (ffi/size type)
Get the size of an ffi type in bytes.
Community Examples / source
cfunction (ffi/struct & types)
Create a struct type definition that can be used to pass structs into native functions. 
Community Examples / source
cfunction (ffi/trampoline cc)
Get a native function pointer that can be used as a callback and passed to C libraries. This callback trampoline has the signature `void trampoline(void \*ctx, void \*userdata)` in the given calling convention. This is the only function signature supported. It is up to the programmer to ensure that the `userdata` argument contains a janet function the will be called with one argument, `ctx` which is an opaque pointer. This pointer can be further inspected with `ffi/read`.
Community Examples / source
cfunction (ffi/write ffi-type data &opt buffer index)
Append a native type to a buffer such as it would appear in memory. This can be used to pass pointers to structs in the ffi, or send C/C++/native structs over the network or to files. Returns a modifed buffer or a new buffer if one is not supplied.
Community Examples / source
macro (fiber-fn flags & body)
A wrapper for making fibers. Same as `(fiber/new (fn [] ;body) flags)`.
Community Examples / source
cfunction (fiber/can-resume? fiber)
Check if a fiber is finished and cannot be resumed.
Community Examples / source
cfunction (fiber/current )
Returns the currently running fiber.
Community Examples / source
cfunction (fiber/getenv fiber)
Gets the environment for a fiber. Returns nil if no such table is set yet.
Community Examples / source
cfunction (fiber/last-value )
Get the last value returned or signaled from the fiber.
Community Examples / source
cfunction (fiber/maxstack fib)
Gets the maximum stack size in janet values allowed for a fiber. While memory for the fiber's stack is not allocated up front, the fiber will not allocated more than this amount and will throw a stack-overflow error if more memory is needed. 
Community Examples / source
cfunction (fiber/new func &opt sigmask)
Create a new fiber with function body func. Can optionally take a set of signals to block from the current parent fiber when called. The mask is specified as a keyword where each character is used to indicate a signal to block. If the ev module is enabled, and this fiber is used as an argument to `ev/go`, these "blocked" signals will result in messages being sent to the supervisor channel. The default sigmask is :y. For example,

 (fiber/new myfun :e123)

blocks error signals and user signals 1, 2 and 3. The signals are as follows:

* :a - block all signals
* :d - block debug signals
* :e - block error signals
* :t - block termination signals: error + user[0-4]
* :u - block user signals
* :y - block yield signals
* :0-9 - block a specific user signal

The sigmask argument also can take environment flags. If any mutually exclusive flags are present, the last flag takes precedence.

* :i - inherit the environment from the current fiber
* :p - the environment table's prototype is the current environment table
Community Examples / source
cfunction (fiber/root )
Returns the current root fiber. The root fiber is the oldest ancestor that does not have a parent.
Community Examples / source
cfunction (fiber/setenv fiber table)
Sets the environment table for a fiber. Set to nil to remove the current environment.
Community Examples / source
cfunction (fiber/setmaxstack fib maxstack)
Sets the maximum stack size in janet values for a fiber. By default, the maximum stack size is usually 8192.
Community Examples / source
cfunction (fiber/status fib)
Get the status of a fiber. The status will be one of:

* :dead - the fiber has finished
* :error - the fiber has errored out
* :debug - the fiber is suspended in debug mode
* :pending - the fiber has been yielded
* :user(0-9) - the fiber is suspended by a user signal
* :alive - the fiber is currently running and cannot be resumed
* :new - the fiber has just been created and not yet run
Community Examples / source
function (fiber? x)
Check if x is a fiber.
Community Examples / source
cfunction (file/close f)
Close a file and release all related resources. When you are done reading a file, close it to prevent a resource leak and let other processes read the file.
Community Examples / source
cfunction (file/flush f)
Flush any buffered bytes to the file system. In most files, writes are buffered for efficiency reasons. Returns the file handle.
Community Examples / source
cfunction (file/open path &opt mode)
Open a file. `path` is an absolute or relative path, and `mode` is a set of flags indicating the mode to open the file in. `mode` is a keyword where each character represents a flag. If the file cannot be opened, returns nil, otherwise returns the new file handle. Mode flags:

* r - allow reading from the file

* w - allow writing to the file

* a - append to the file

Following one of the initial flags, 0 or more of the following flags can be appended:

* b - open the file in binary mode (rather than text mode)

* + - append to the file instead of overwriting it

* n - error if the file cannot be opened instead of returning nil
Community Examples / source
cfunction (file/read f what &opt buf)
Read a number of bytes from a file `f` into a buffer. A buffer `buf` can be provided as an optional third argument, otherwise a new buffer is created. `what` can either be an integer or a keyword. Returns the buffer with file contents. Values for `what`:

* :all - read the whole file

* :line - read up to and including the next newline character

* n (integer) - read up to n bytes from the file
Community Examples / source
cfunction (file/seek f &opt whence n)
Jump to a relative location in the file `f`. `whence` must be one of:

* :cur - jump relative to the current file location

* :set - jump relative to the beginning of the file

* :end - jump relative to the end of the file

By default, `whence` is :cur. Optionally a value `n` may be passed for the relative number of bytes to seek in the file. `n` may be a real number to handle large files of more than 4GB. Returns the file handle.
Community Examples / source
cfunction (file/tell f)
Get the current value of the file position for file `f`.
Community Examples / source
cfunction (file/temp )
Open an anonymous temporary file that is removed on close. Raises an error on failure.
Community Examples / source
cfunction (file/write f bytes)
Writes to a file. 'bytes' must be string, buffer, or symbol. Returns the file.
Community Examples / source
function (filter pred ind)
Given a predicate, take only elements from an array or tuple for
which `(pred element)` is truthy. Returns a new array.
Community Examples / source
function (find pred ind &opt dflt)
Find the first value in an indexed collection that satisfies a predicate. Returns
`dflt` if not found.
Community Examples / source
function (find-index pred ind &opt dflt)
Find the index of indexed type for which `pred` is true. Returns `dflt` if not found.
Community Examples / source
function (first xs)
Get the first element from an indexed data structure.
Community Examples / source
function (flatten xs)
Takes a nested array (tree) `xs` and returns the depth first traversal of
it. Returns a new array.
Community Examples / source
function (flatten-into into xs)
Takes a nested array (tree) `xs` and appends the depth first traversal of
`xs` to array `into`. Returns `into`.
Community Examples / source
cfunction (flush )
Flush `(dyn :out stdout)` if it is a file, otherwise do nothing.
Community Examples / source
function (flycheck path &keys kwargs)
Check a file for errors without running the file. Found errors will be printed to stderr
in the usual format. Macros will still be executed, however, so
arbitrary execution is possible. Other arguments are the same as `dofile`. `path` can also be
a file value such as stdin. Returns nil.
Community Examples / source
macro (for i start stop & body)
Do a C-style for-loop for side effects. Returns nil.
Community Examples / source
macro (forever & body)
Evaluate body forever in a loop, or until a break statement.
Community Examples / source
macro (forv i start stop & body)
Do a C-style for-loop for side effects. The iteration variable `i`
can be mutated in the loop, unlike normal `for`. Returns nil.
Community Examples / source
function (freeze x)
Freeze an object (make it immutable) and do a deep copy, making
child values also immutable. Closures, fibers, and abstract types
will not be recursively frozen, but all other types will.
Community Examples / source
function (frequencies ind)
Get the number of occurrences of each value in an indexed data structure.
Community Examples / source
function (from-pairs ps)
Takes a sequence of pairs and creates a table from each pair. It is the inverse of
`pairs` on a table. Returns a new table.
Community Examples / source
function (function? x)
Check if x is a function (not a cfunction).
Community Examples / source
cfunction (gccollect )
Run garbage collection. You should probably not call this manually.
Community Examples / source
cfunction (gcinterval )
Returns the integer number of bytes to allocate before running an iteration of garbage collection.
Community Examples / source
cfunction (gcsetinterval interval)
Set an integer number of bytes to allocate before running garbage collection. Low values for interval will be slower but use less memory. High values will be faster but use more memory.
Community Examples / source
macro (generate head & body)
Create a generator expression using the `loop` syntax. Returns a fiber
that yields all values inside the loop in order. See `loop` for details.
Example:
# An infinite stream of random numbers, but doubled.
(def g (generate [_ :iterate true :repeat 2] (math/random)))
# -> <fiber 0x5562863141E0>

(resume g) # -> 0.487181
(resume g) # -> 0.487181
(resume g) # -> 0.507917
(resume g) # -> 0.507917
# ...
Community Examples / source
cfunction (gensym )
Returns a new symbol that is unique across the runtime. This means it will not collide with any already created symbols during compilation, so it can be used in macros to generate automatic bindings.
Community Examples / source
function (get ds key &opt dflt)
Get the value mapped to key in data structure ds, and return dflt or nil if not found. Similar to in, but will not throw an error if the key is invalid for the data structure unless the data structure is an abstract type. In that case, the abstract type getter may throw an error.
Community Examples /
function (get-in ds ks &opt dflt)
Access a value in a nested data structure. Looks into the data structure via
a sequence of keys. If value is not found, and `dflt` is provided, returns `dflt`.
Community Examples / source
cfunction (getline &opt prompt buf env)
Reads a line of input into a buffer, including the newline character, using a prompt. An optional environment table can be provided for auto-complete. Returns the modified buffer. Use this function to implement a simple interface for a terminal program.
Community Examples / source
cfunction (getproto x)
Get the prototype of a table or struct. Will return nil if `x` has no prototype.
Community Examples / source
function (group-by f ind)
Group elements of `ind` by a function `f` and put the results into a new table. The keys of
the table are the distinct return values from calling `f` on the elements of `ind`. The values
of the table are arrays of all elements of `ind` for which `f` called on the element equals
that corresponding key.
Community Examples / source
cfunction (hash value)
Gets a hash for any value. The hash is an integer can be used as a cheap hash function for all values. If two values are strictly equal, then they will have the same hash value.
Community Examples / source
function (idempotent? x)
Check if x is a value that evaluates to itself when compiled.
Community Examples / source
function (identity x)
A function that returns its argument.
Community Examples / source
macro (if-let bindings tru &opt fal)
Make multiple bindings, and if all are truthy,
evaluate the `tru` form. If any are false or nil, evaluate
the `fal` form. Bindings have the same syntax as the `let` macro.
Community Examples / source
macro (if-not condition then &opt else)
Shorthand for `(if (not condition) else then)`.
Community Examples / source
macro (if-with [binding ctor dtor] truthy &opt falsey)
Similar to `with`, but if binding is false or nil, evaluates
the falsey path. Otherwise, evaluates the truthy path. In both cases,
`ctor` is bound to binding.
Community Examples / source
macro (import path & args)
Import a module. First requires the module, and then merges its
symbols into the current environment, prepending a given prefix as needed.
(use the :as or :prefix option to set a prefix). If no prefix is provided,
use the name of the module as a prefix. One can also use "`:export true`"
to re-export the imported symbols. If "`:exit true`" is given as an argument,
any errors encountered at the top level in the module will cause `(os/exit 1)`
to be called. Dynamic bindings will NOT be imported. Use :fresh to bypass the
module cache.
Community Examples / source
function (import* path & args)
Function form of `import`. Same parameters, but the path
and other symbol parameters should be strings instead.
Community Examples / source
function (in ds key &opt dflt)
Get value in ds at key, works on associative data structures. Arrays, tuples, tables, structs, strings, symbols, and buffers are all associative and can be used. Arrays, tuples, strings, buffers, and symbols must use integer keys that are in bounds or an error is raised. Structs and tables can take any value as a key except nil and will return nil or dflt if not found.
Community Examples /
function (inc x)
Returns x + 1.
Community Examples / source
function (index-of x ind &opt dflt)
Find the first key associated with a value x in a data structure, acting like a reverse lookup.
Will not look at table prototypes.
Returns `dflt` if not found.
Community Examples / source
function (indexed? x)
Check if x is an array or tuple.
Community Examples / source
cfunction (int/s64 value)
Create a boxed signed 64 bit integer from a string value.
Community Examples / source
cfunction (int/to-bytes value &opt endianness buffer)
Write the bytes of an `int/s64` or `int/u64` into a buffer.
The `buffer` parameter specifies an existing buffer to write to, if unset a new buffer will be created.
Returns the modified buffer.
The `endianness` paramater indicates the byte order:
- `nil` (unset): system byte order
- `:le`: little-endian, least significant byte first
- `:be`: big-endian, most significant byte first
Community Examples / source
cfunction (int/to-number value)
Convert an int/u64 or int/s64 to a number. Fails if the number is out of range for an int32.
Community Examples / source
cfunction (int/u64 value)
Create a boxed unsigned 64 bit integer from a string value.
Community Examples / source
cfunction (int? x)
Check if x can be exactly represented as a 32 bit signed two's complement integer.
Community Examples / source
function (interleave & cols)
Returns an array of the first elements of each col, then the second elements, etc.
Community Examples / source
function (interpose sep ind)
Returns a sequence of the elements of `ind` separated by
`sep`. Returns a new array.
Community Examples / source
function (invert ds)
Given an associative data structure `ds`, returns a new table where the
keys of `ds` are the values, and the values are the keys. If multiple keys
in `ds` are mapped to the same value, only one of those values will
become a key in the returned table.
Community Examples / source
string janet/build
The build identifier of the running janet program.
Community Examples /
number janet/config-bits
The flag set of config options from janetconf.h which is used to check if native modules are compatible with the host program.
Community Examples /
string janet/version
The version number of the running janet program.
Community Examples /
macro (juxt & funs)
Macro form of `juxt*`. Same behavior but more efficient.
Community Examples / source
function (juxt* & funs)
Returns the juxtaposition of functions. In other words,
`((juxt* a b c) x)` evaluates to `[(a x) (b x) (c x)]`.
Community Examples / source
function (keep pred ind)
Given a predicate `pred`, return a new array containing the truthy results
of applying `pred` to each element in the indexed collection `ind`. This is
different from `filter` which returns an array of the original elements where
the predicate is truthy.
Community Examples / source
function (keys x)
Get the keys of an associative data structure.
Community Examples / source
cfunction (keyword & xs)
Creates a keyword by concatenating the elements of `xs` together. If an element is not a byte sequence, it is converted to bytes via `describe`. Returns the new keyword.
Community Examples / source
cfunction (keyword/slice bytes &opt start end)
Same as string/slice, but returns a keyword.
Community Examples / source
function (keyword? x)
Check if x is a keyword.
Community Examples / source
function (kvs dict)
Takes a table or struct and returns and array of key value pairs
like `@[k v k v ...]`. Returns a new array.
Community Examples / source
macro (label name & body)
Set a label point that is lexically scoped. `name` should be a symbol
that will be bound to the label.
Community Examples / source
function (last xs)
Get the last element from an indexed data structure.
Community Examples / source
function (length ds)
Returns the length or count of a data structure in constant time as an integer. For structs and tables, returns the number of key-value pairs in the data structure.
Community Examples /
macro (let bindings & body)
Create a scope and bind values to symbols. Each pair in `bindings` is
assigned as if with `def`, and the body of the `let` form returns the last
value.
Community Examples / source
function (load-image image)
The inverse operation to `make-image`. Returns an environment.
Community Examples / source
table load-image-dict
A table used in combination with `unmarshal` to unmarshal byte sequences created
by `make-image`, such that `(load-image bytes)` is the same as `(unmarshal bytes load-image-dict)`.
Community Examples / source
macro (loop head & body)
A general purpose loop macro. This macro is similar to the Common Lisp loop
macro, although intentionally much smaller in scope. The head of the loop
should be a tuple that contains a sequence of either bindings or
conditionals. A binding is a sequence of three values that define something
to loop over. Bindings are written in the format:

 binding :verb object/expression

where `binding` is a binding as passed to def, `:verb` is one of a set of
keywords, and `object` is any expression. Each subsequent binding creates a
nested loop within the loop created by the previous binding.

The available verbs are:

* `:iterate` -- repeatedly evaluate and bind to the expression while it is
 truthy.

* `:range` -- loop over a range. The object should be a two-element tuple with
 a start and end value, and an optional positive step. The range is half
 open, [start, end).

* `:range-to` -- same as :range, but the range is inclusive [start, end].

* `:down` -- loop over a range, stepping downwards. The object should be a
 two-element tuple with a start and (exclusive) end value, and an optional
 (positive!) step size.

* `:down-to` -- same as :down, but the range is inclusive [start, end].

* `:keys` -- iterate over the keys in a data structure.

* `:pairs` -- iterate over the key-value pairs as tuples in a data structure.

* `:in` -- iterate over the values in a data structure or fiber.

`loop` also accepts conditionals to refine the looping further. Conditionals are of
the form:

   :modifier argument

where `:modifier` is one of a set of keywords, and `argument` is keyword-dependent.
`:modifier` can be one of:

* `:while expression` -- breaks from the current loop if `expression` is
  falsey.

* `:until expression` -- breaks from the current loop if `expression` is
  truthy.

* `:let bindings` -- defines bindings inside the current loop as passed to the
  `let` macro.

* `:before form` -- evaluates a form for a side effect before the next inner
  loop.

* `:after form` -- same as `:before`, but the side effect happens after the
  next inner loop.

* `:repeat n` -- repeats the next inner loop `n` times.

* `:when condition` -- only evaluates the current loop body when `condition`
  is true.

The `loop` macro always evaluates to nil.
Example:
# -> prints 0123456789 (not followed by newline)
(loop [x :range [0 10]]
  (prin x))

# Cartesian product (nested loops)

# -> prints 00010203101112132021222330313233
# Same as (for x 0 4 (for y 0 4 (prin x y)))
(loop [x :range [0 4]
       y :range [0 4]]
  (prin x y))

# -> prints bytes of "hello, world" as numbers
(loop [character :in "hello, world"]
  (print character))

# -> prints 1, 2, and 3, in an unspecified order
(loop [value :in {:a 1 :b 2 :c 3}]
  (print value))

# -> prints 0 to 99 inclusive
(loop [x :in (range 100)]
  (print x))

# Complex body
(loop [x :in (range 10)]
  (print x)
  (print (inc c))
  (print (+ x 2)))

# Iterate over keys
(loop [k :keys {:a 1 :b 2 :c 3}]
  (print k))
# print a, b, and c in an unspecified order

(loop [index :keys [:a :b :c :d]]
  (print index))
#  print 0, 1, 2, and 3 in order.

(defn print-pairs
  [x]
  (loop [[k v] :pairs x]
    (printf "[%v]=%v" k v)))

(print-pairs [:a :b :c])
# [0]=:a
# [1]=:b
# [2]=:c

(print-pairs {:a 1 :b 2 :c 3})
# [:a]=1
# [:b]=2
# [:c]=3

# Some modifiers - allow early termination and conditional execution
# of the loop

(loop [x :range [0 100] :when (even? x)]
  (print x))
# prints even numbers 0, 2, 4, ..., 98

(loop [x :range [1 100] :while (pos? (% x 7))]
  (print x))
# prints 1, 2, 3, 4, 5, 6

# Consume fibers as generators
(def f
  (fiber/new
    (fn []
      (for i 0 100
        (yield i)))))

(loop [x :in f]
  (print x))
# print 0, 1, 2, ... 99

# Modifiers in nested loops

(loop [x :range [0 10]
      :after (print)
       y :range [0 x]]
  (prin y " "))
# 0
# 0 1
# 0 1 2
# 0 1 2 3
# 0 1 2 3 4
# 0 1 2 3 4 5
# 0 1 2 3 4 5 6
# 0 1 2 3 4 5 6 7
# 0 1 2 3 4 5 6 7 8
Community Examples / source
function (macex x &opt on-binding)
Expand macros completely.
`on-binding` is an optional callback for whenever a normal symbolic binding
is encountered. This allows macros to easily see all bindings used by their
arguments by calling `macex` on their contents. The binding itself is also
replaced by the value returned by `on-binding` within the expanded macro.
Community Examples / source
function (macex1 x &opt on-binding)
Expand macros in a form, but do not recursively expand macros.
See `macex` docs for info on `on-binding`.
Community Examples / source
function (maclintf level fmt & args)
When inside a macro, call this function to add a linter warning. Takes
a `fmt` argument like `string/format`, which is used to format the message.
Community Examples / source
function (make-env &opt parent)
Create a new environment table. The new environment
will inherit bindings from the parent environment, but new
bindings will not pollute the parent environment.
Community Examples / source
function (make-image env)
Create an image from an environment returned by `require`.
Returns the image source as a string.
Community Examples / source
table make-image-dict
A table used in combination with `marshal` to marshal code (images), such that
`(make-image x)` is the same as `(marshal x make-image-dict)`.
Community Examples / source
function (map f & inds)
Map a function over every value in a data structure and
return an array of the results.
Community Examples / source
function (mapcat f ind)
Map a function over every element in an array or tuple and
use `array/concat` to concatenate the results.
Community Examples / source
cfunction (marshal x &opt reverse-lookup buffer no-cycles)
Marshal a value into a buffer and return the buffer. The buffer can then later be unmarshalled to reconstruct the initial value. Optionally, one can pass in a reverse lookup table to not marshal aliased values that are found in the table. Then a forward lookup table can be used to recover the original value when unmarshalling.
Community Examples / source
macro (match x & cases)
Pattern matching. Match an expression `x` against any number of cases.
Each case is a pattern to match against, followed by an expression to
evaluate to if that case is matched. Legal patterns are:

* symbol -- a pattern that is a symbol will match anything, binding `x`'s
 value to that symbol.

* array or bracket tuple -- an array or bracket tuple will match only if
 all of its elements match the corresponding elements in `x`.
 Use `& rest` at the end of an array or bracketed tuple to bind all remaining values to `rest`.

* table or struct -- a table or struct will match if all values match with
 the corresponding values in `x`.

* tuple -- a tuple pattern will match if its first element matches, and the
 following elements are treated as predicates and are true.

* `_` symbol -- the last special case is the `_` symbol, which is a wildcard
 that will match any value without creating a binding.

While a symbol pattern will ordinarily match any value, the pattern `(@ <sym>)`,
where <sym> is any symbol, will attempt to match `x` against a value
already bound to `<sym>`, rather than matching and rebinding it.

Any other value pattern will only match if it is equal to `x`.
Quoting a pattern with `'` will also treat the value as a literal value to match against.
Community Examples / source
number math/-inf
The number representing negative infinity
Community Examples / source
cfunction (math/abs x)
Return the absolute value of x.
Community Examples / source
cfunction (math/acos x)
Returns the arccosine of x.
Community Examples / source
cfunction (math/acosh x)
Returns the hyperbolic arccosine of x.
Community Examples / source
cfunction (math/asin x)
Returns the arcsin of x.
Community Examples / source
cfunction (math/asinh x)
Returns the hyperbolic arcsine of x.
Community Examples / source
cfunction (math/atan x)
Returns the arctangent of x.
Community Examples / source
cfunction (math/atan2 y x)
Returns the arctangent of y/x. Works even when x is 0.
Community Examples / source
cfunction (math/atanh x)
Returns the hyperbolic arctangent of x.
Community Examples / source
cfunction (math/cbrt x)
Returns the cube root of x.
Community Examples / source
cfunction (math/ceil x)
Returns the smallest integer value number that is not less than x.
Community Examples / source
cfunction (math/cos x)
Returns the cosine of x.
Community Examples / source
cfunction (math/cosh x)
Returns the hyperbolic cosine of x.
Community Examples / source
number math/e
The base of the natural log.
Community Examples / source
cfunction (math/erf x)
Returns the error function of x.
Community Examples / source
cfunction (math/erfc x)
Returns the complementary error function of x.
Community Examples / source
cfunction (math/exp x)
Returns e to the power of x.
Community Examples / source
cfunction (math/exp2 x)
Returns 2 to the power of x.
Community Examples / source
cfunction (math/expm1 x)
Returns e to the power of x minus 1.
Community Examples / source
cfunction (math/floor x)
Returns the largest integer value number that is not greater than x.
Community Examples / source
cfunction (math/gamma x)
Returns gamma(x).
Community Examples / source
cfunction (math/gcd x y)
Returns the greatest common divisor between x and y.
Community Examples / source
cfunction (math/hypot a b)
Returns c from the equation c^2 = a^2 + b^2.
Community Examples / source
number math/inf
The number representing positive infinity
Community Examples / source
number math/int-max
The maximum contiguous integer represtenable by a double (-(2^53))
Community Examples / source
number math/int-min
The minimum contiguous integer representable by a double (2^53)
Community Examples / source
number math/int32-max
The maximum contiguous integer represtenable by a 32 bit signed integer
Community Examples / source
number math/int32-min
The minimum contiguous integer representable by a 32 bit signed integer
Community Examples / source
cfunction (math/lcm x y)
Returns the least common multiple of x and y.
Community Examples / source
cfunction (math/log x)
Returns the natural logarithm of x.
Community Examples / source
cfunction (math/log-gamma x)
Returns log-gamma(x).
Community Examples / source
cfunction (math/log10 x)
Returns the log base 10 of x.
Community Examples / source
cfunction (math/log1p x)
Returns (log base e of x) + 1 more accurately than (+ (math/log x) 1)
Community Examples / source
cfunction (math/log2 x)
Returns the log base 2 of x.
Community Examples / source
number math/nan
Not a number (IEEE-754 NaN)
Community Examples / source
cfunction (math/next x y)
Returns the next representable floating point value after x in the direction of y.
Community Examples / source
number math/pi
The value pi.
Community Examples / source
cfunction (math/pow a x)
Returns a to the power of x.
Community Examples / source
cfunction (math/random )
Returns a uniformly distributed random number between 0 and 1.
Community Examples / source
cfunction (math/rng &opt seed)
Creates a Psuedo-Random number generator, with an optional seed. The seed should be an unsigned 32 bit integer or a buffer. Do not use this for cryptography. Returns a core/rng abstract type.
Community Examples / source
cfunction (math/rng-buffer rng n &opt buf)
Get n random bytes and put them in a buffer. Creates a new buffer if no buffer is provided, otherwise appends to the given buffer. Returns the buffer.
Community Examples / source
cfunction (math/rng-int rng &opt max)
Extract a random integer in the range [0, max) for max > 0 from the RNG. If max is 0, return 0. If no max is given, the default is 2^31 - 1.
Community Examples / source
cfunction (math/rng-uniform rng)
Extract a random number in the range [0, 1) from the RNG.
Community Examples / source
cfunction (math/round x)
Returns the integer nearest to x.
Community Examples / source
cfunction (math/seedrandom seed)
Set the seed for the random number generator. `seed` should be an integer or a buffer.
Community Examples / source
cfunction (math/sin x)
Returns the sine of x.
Community Examples / source
cfunction (math/sinh x)
Returns the hyperbolic sine of x.
Community Examples / source
cfunction (math/sqrt x)
Returns the square root of x.
Community Examples / source
cfunction (math/tan x)
Returns the tangent of x.
Community Examples / source
cfunction (math/tanh x)
Returns the hyperbolic tangent of x.
Community Examples / source
cfunction (math/trunc x)
Returns the integer between x and 0 nearest to x.
Community Examples / source
function (max & args)
Returns the numeric maximum of the arguments.
Community Examples / source
function (max-of args)
Returns the numeric maximum of the argument sequence.
Community Examples / source
function (mean xs)
Returns the mean of xs. If empty, returns NaN.
Community Examples / source
cfunction (memcmp a b &opt len offset-a offset-b)
Compare memory. Takes two byte sequences `a` and `b`, and return 0 if they have identical contents, a negative integer if a is less than b, and a positive integer if a is greater than b. Optionally take a length and offsets to compare slices of the bytes sequences.
Community Examples / source
function (merge & colls)
Merges multiple tables/structs into one new table. If a key appears in more than one
collection in `colls`, then later values replace any previous ones.
Returns the new table.
Community Examples / source
function (merge-into tab & colls)
Merges multiple tables/structs into table `tab`. If a key appears in more than one
collection in `colls`, then later values replace any previous ones. Returns `tab`.
Community Examples / source
function (merge-module target source &opt prefix export)
Merge a module source into the `target` environment with a `prefix`, as with the `import` macro.
This lets users emulate the behavior of `import` with a custom module table.
If `export` is truthy, then merged functions are not marked as private. Returns
the modified target environment.
Community Examples / source
function (min & args)
Returns the numeric minimum of the arguments.
Community Examples / source
function (min-of args)
Returns the numeric minimum of the argument sequence.
Community Examples / source
function (mod dividend divisor)
Returns the modulo of dividend / divisor.
Community Examples /
function (module/add-paths ext loader)
Add paths to `module/paths` for a given loader such that
the generated paths behave like other module types, including
relative imports and syspath imports. `ext` is the file extension
to associate with this module type, including the dot. `loader` is the
keyword name of a loader in `module/loaders`. Returns the modified `module/paths`.
Community Examples / source
table module/cache
A table, mapping loaded module identifiers to their environments.
Community Examples / source
cfunction (module/expand-path path template)
Expands a path template as found in `module/paths` for `module/find`. This takes in a path (the argument to require) and a template string, to expand the path to a path that can be used for importing files. The replacements are as follows:

* :all: -- the value of path verbatim.

* :@all: -- Same as :all:, but if `path` starts with the @ character,
 the first path segment is replaced with a dynamic binding
           `(dyn <first path segment as keyword>)`.

* :cur: -- the current file, or (dyn :current-file)

* :dir: -- the directory containing the current file

* :name: -- the name component of path, with extension if given

* :native: -- the extension used to load natives, .so or .dll

* :sys: -- the system path, or (dyn :syspath)
Community Examples / source
function (module/find path)
Try to match a module or path name from the patterns in `module/paths`.
Returns a tuple (fullpath kind) where the kind is one of :source, :native,
or :image if the module is found, otherwise a tuple with nil followed by
an error message.
Community Examples / source
table module/loaders
A table of loading method names to loading functions.
This table lets `require` and `import` load many different kinds
of files as modules.
Community Examples / source
table module/loading
A table, mapping currently loading modules to true. Used to prevent
circular dependencies.
Community Examples / source
array module/paths
The list of paths to look for modules, templated for `module/expand-path`.
Each element is a two-element tuple, containing the path
template and a keyword :source, :native, or :image indicating how
`require` should load files found at these paths.

A tuple can also
contain a third element, specifying a filter that prevents `module/find`
from searching that path template if the filter doesn't match the input
path. The filter can be a string or a predicate function, and
is often a file extension, including the period.
Community Examples / source
function (module/value module sym &opt private)
Given a module table, get the value bound to a symbol `sym`. If `private` is
truthy, will also resolve private module symbols. If no binding is found, will return
nil.
Community Examples / source
function (nan? x)
Check if x is NaN.
Community Examples / source
cfunction (nat? x)
Check if x can be exactly represented as a non-negative 32 bit signed two's complement integer.
Community Examples / source
cfunction (native path &opt env)
Load a native module from the given path. The path must be an absolute or relative path on the file system, and is usually a .so file on Unix systems, and a .dll file on Windows. Returns an environment table that contains functions and other values from the native module.
Community Examples / source
function (neg? x)
Check if x is less than 0.
Community Examples / source
cfunction (net/accept stream &opt timeout)
Get the next connection on a server stream. This would usually be called in a loop in a dedicated fiber. Takes an optional timeout in seconds, after which will return nil. Returns a new duplex stream which represents a connection to the client.
Community Examples / source
cfunction (net/accept-loop stream handler)
Shorthand for running a server stream that will continuously accept new connections. Blocks the current fiber until the stream is closed, and will return the stream.
Community Examples / source
cfunction (net/address host port &opt type multi)
Look up the connection information for a given hostname, port, and connection type. Returns a handle that can be used to send datagrams over network without establishing a connection. On Posix platforms, you can use :unix for host to connect to a unix domain socket, where the name is given in the port argument. On Linux, abstract unix domain sockets are specified with a leading '@' character in port. If `multi` is truthy, will return all address that match in an array instead of just the first.
Community Examples / source
cfunction (net/address-unpack address)
Given an address returned by net/address, return a host, port pair. Unix domain sockets will have only the path in the returned tuple.
Community Examples / source
cfunction (net/chunk stream nbytes &opt buf timeout)
Same a net/read, but will wait for all n bytes to arrive rather than return early. Takes an optional timeout in seconds, after which will return nil.
Community Examples / source
function (net/close stream)
Alias for `ev/close`.
Community Examples / source
cfunction (net/connect host port &opt type bindhost bindport)
Open a connection to communicate with a server. Returns a duplex stream that can be used to communicate with the server. Type is an optional keyword to specify a connection type, either :stream or :datagram. The default is :stream. Bindhost is an optional string to select from what address to make the outgoing connection, with the default being the same as using the OS's preferred address. 
Community Examples / source
cfunction (net/flush stream)
Make sure that a stream is not buffering any data. This temporarily disables Nagle's algorithm. Use this to make sure data is sent without delay. Returns stream.
Community Examples / source
cfunction (net/listen host port &opt type)
Creates a server. Returns a new stream that is neither readable nor writeable. Use net/accept or net/accept-loop be to handle connections and start the server. The type parameter specifies the type of network connection, either a :stream (usually tcp), or :datagram (usually udp). If not specified, the default is :stream. The host and port arguments are the same as in net/address.
Community Examples / source
cfunction (net/localname stream)
Gets the local address and port in a tuple in that order.
Community Examples / source
cfunction (net/peername stream)
Gets the remote peer's address and port in a tuple in that order.
Community Examples / source
cfunction (net/read stream nbytes &opt buf timeout)
Read up to n bytes from a stream, suspending the current fiber until the bytes are available. `n` can also be the keyword `:all` to read into the buffer until end of stream. If less than n bytes are available (and more than 0), will push those bytes and return early. Takes an optional timeout in seconds, after which will return nil. Returns a buffer with up to n more bytes in it, or raises an error if the read failed.
Community Examples / source
cfunction (net/recv-from stream nbytes buf &opt timeout)
Receives data from a server stream and puts it into a buffer. Returns the socket-address the packet came from. Takes an optional timeout in seconds, after which will return nil.
Community Examples / source
cfunction (net/send-to stream dest data &opt timeout)
Writes a datagram to a server stream. dest is a the destination address of the packet. Takes an optional timeout in seconds, after which will return nil. Returns stream.
Community Examples / source
function (net/server host port &opt handler type)
Start a server asynchronously with `net/listen` and `net/accept-loop`. Returns the new server stream.
Community Examples / source
cfunction (net/shutdown stream &opt mode)
Stop communication on this socket in a graceful manner, either in both directions or just reading/writing from the stream. The `mode` parameter controls which communication to stop on the socket. 

* `:wr` is the default and prevents both reading new data from the socket and writing new data to the socket.
* `:r` disables reading new data from the socket.
* `:w` disable writing data to the socket.

Returns the original socket.
Community Examples / source
cfunction (net/write stream data &opt timeout)
Write data to a stream, suspending the current fiber until the write completes. Takes an optional timeout in seconds, after which will return nil. Returns nil, or raises an error if the write failed.
Community Examples / source
function (next ds &opt key)
Gets the next key in a data structure. Can be used to iterate through the keys of a data structure in an unspecified order. Keys are guaranteed to be seen only once per iteration if they data structure is not mutated during iteration. If key is nil, next returns the first key. If next returns nil, there are no more keys to iterate through.
Community Examples /
function (nil? x)
Check if x is nil.
Community Examples / source
cfunction (not x)
Returns the boolean inverse of x.
Community Examples / source
function (not= & xs)
Check if any values in xs are not equal. Returns a boolean.
Community Examples /
function (number? x)
Check if x is a number.
Community Examples / source
function (odd? x)
Check if x is odd.
Community Examples / source
function (one? x)
Check if x is equal to 1.
Community Examples / source
macro (or & forms)
Evaluates to the last argument if all preceding elements are falsey, otherwise
evaluates to the first truthy element.
Community Examples / source
cfunction (os/arch )
Check the ISA that janet was compiled for. Returns one of:

* :x86

* :x64

* :arm

* :aarch64

* :riscv32

* :riscv64

* :sparc

* :wasm

* :unknown
Community Examples / source
cfunction (os/cd path)
Change current directory to path. Returns nil on success, errors on failure.
Community Examples / source
cfunction (os/chmod path mode)
Change file permissions, where `mode` is a permission string as returned by `os/perm-string`, or an integer as returned by `os/perm-int`. When `mode` is an integer, it is interpreted as a Unix permission value, best specified in octal, like 8r666 or 8r400. Windows will not differentiate between user, group, and other permissions, and thus will combine all of these permissions. Returns nil.
Community Examples / source
cfunction (os/clock )
Return the number of whole + fractional seconds since some fixed point in time. The clock is guaranteed to be non-decreasing in real time.
Community Examples / source
cfunction (os/compiler )
Get the compiler used to compile the interpreter. Returns one of:

* :gcc

* :clang

* :msvc

* :unknown

Community Examples / source
cfunction (os/cpu-count &opt dflt)
Get an approximate number of CPUs available on for this process to use. If unable to get an approximation, will return a default value dflt.
Community Examples / source
cfunction (os/cryptorand n &opt buf)
Get or append `n` bytes of good quality random data provided by the OS. Returns a new buffer or `buf`.
Community Examples / source
cfunction (os/cwd )
Returns the current working directory.
Community Examples / source
cfunction (os/date &opt time local)
Returns the given time as a date struct, or the current time if `time` is not given. Returns a struct with following key values. Note that all numbers are 0-indexed. Date is given in UTC unless `local` is truthy, in which case the date is formatted for the local timezone.

* :seconds - number of seconds [0-61]

* :minutes - number of minutes [0-59]

* :hours - number of hours [0-23]

* :month-day - day of month [0-30]

* :month - month of year [0, 11]

* :year - years since year 0 (e.g. 2019)

* :week-day - day of the week [0-6]

* :year-day - day of the year [0-365]

* :dst - if Day Light Savings is in effect
Community Examples / source
cfunction (os/dir dir &opt array)
Iterate over files and subdirectories in a directory. Returns an array of paths parts, with only the file name or directory name and no prefix.
Community Examples / source
cfunction (os/environ )
Get a copy of the OS environment table.
Community Examples / source
cfunction (os/execute args &opt flags env)
Execute a program on the system and pass it string arguments. `flags` is a keyword that modifies how the program will execute.
* :e - enables passing an environment to the program. Without :e, the current environment is inherited.
* :p - allows searching the current PATH for the binary to execute. Without this flag, binaries must use absolute paths.
* :x - raise error if exit code is non-zero.
* :d - Don't try and terminate the process on garbage collection (allow spawning zombies).
`env` is a table or struct mapping environment variables to values. It can also contain the keys :in, :out, and :err, which allow redirecting stdio in the subprocess. These arguments should be core/file values. Returns the exit status of the program.
Community Examples / source
cfunction (os/exit &opt x)
Exit from janet with an exit code equal to x. If x is not an integer, the exit with status equal the hash of x.
Community Examples / source
cfunction (os/getenv variable &opt dflt)
Get the string value of an environment variable.
Community Examples / source
cfunction (os/link oldpath newpath &opt symlink)
Create a link at newpath that points to oldpath and returns nil. Iff symlink is truthy, creates a symlink. Iff symlink is falsey or not provided, creates a hard link. Does not work on Windows.
Community Examples / source
cfunction (os/lstat path &opt tab|key)
Like os/stat, but don't follow symlinks.
Community Examples / source
cfunction (os/mkdir path)
Create a new directory. The path will be relative to the current directory if relative, otherwise it will be an absolute path. Returns true if the directory was created, false if the directory already exists, and errors otherwise.
Community Examples / source
cfunction (os/mktime date-struct &opt local)
Get the broken down date-struct time expressed as the number of seconds since January 1, 1970, the Unix epoch. Returns a real number. Date is given in UTC unless `local` is truthy, in which case the date is computed for the local timezone.

Inverse function to os/date.
Community Examples / source
cfunction (os/open path &opt flags mode)
Create a stream from a file, like the POSIX open system call. Returns a new stream. `mode` should be a file mode as passed to `os/chmod`, but only if the create flag is given. The default mode is 8r666. Allowed flags are as follows:

 * :r - open this file for reading
 * :w - open this file for writing
 * :c - create a new file (O\_CREATE)
 * :e - fail if the file exists (O\_EXCL)
 * :t - shorten an existing file to length 0 (O\_TRUNC)

Posix-only flags:

 * :a - append to a file (O\_APPEND)
 * :x - O\_SYNC
 * :C - O\_NOCTTY

Windows-only flags:

 * :R - share reads (FILE\_SHARE\_READ)
 * :W - share writes (FILE\_SHARE\_WRITE)
  * :D - share deletes (FILE\_SHARE\_DELETE)
  * :H - FILE\_ATTRIBUTE\_HIDDEN
  * :O - FILE\_ATTRIBUTE\_READONLY
  * :F - FILE\_ATTRIBUTE\_OFFLINE
  * :T - FILE\_ATTRIBUTE\_TEMPORARY
  * :d - FILE\_FLAG\_DELETE\_ON\_CLOSE
  * :b - FILE\_FLAG\_NO\_BUFFERING
Community Examples / source
cfunction (os/perm-int bytes)
Parse a 9-character permission string and return an integer that can be used by chmod.
Community Examples / source
cfunction (os/perm-string int)
Convert a Unix octal permission value from a permission integer as returned by `os/stat` to a human readable string, that follows the formatting of Unix tools like `ls`. Returns the string as a 9-character string of r, w, x and - characters. Does not include the file/directory/symlink character as rendered by `ls`.
Community Examples / source
cfunction (os/pipe )
Create a readable stream and a writable stream that are connected. Returns a two-element tuple where the first element is a readable stream and the second element is the writable stream.
Community Examples / source
cfunction (os/proc-close proc)
Wait on a process if it has not been waited on, and close pipes created by `os/spawn` if they have not been closed. Returns nil.
Community Examples / source
cfunction (os/proc-kill proc &opt wait)
Kill a subprocess by sending SIGKILL to it on posix systems, or by closing the process handle on windows. If `wait` is truthy, will wait for the process to finish and returns the exit code. Otherwise, returns `proc`.
Community Examples / source
cfunction (os/proc-wait proc)
Block until the subprocess completes. Returns the subprocess return code.
Community Examples / source
cfunction (os/readlink path)
Read the contents of a symbolic link. Does not work on Windows.
Community Examples / source
cfunction (os/realpath path)
Get the absolute path for a given path, following ../, ./, and symlinks. Returns an absolute path as a string.
Community Examples / source
cfunction (os/rename oldname newname)
Rename a file on disk to a new path. Returns nil.
Community Examples / source
cfunction (os/rm path)
Delete a file. Returns nil.
Community Examples / source
cfunction (os/rmdir path)
Delete a directory. The directory must be empty to succeed.
Community Examples / source
cfunction (os/setenv variable value)
Set an environment variable.
Community Examples / source
cfunction (os/shell str)
Pass a command string str directly to the system shell.
Community Examples / source
cfunction (os/sleep n)
Suspend the program for `n` seconds. `n` can be a real number. Returns nil.
Community Examples / source
cfunction (os/spawn args &opt flags env)
Execute a program on the system and return a handle to the process. Otherwise, takes the same arguments as `os/execute`. Does not wait for the process. For each of the :in, :out, and :err keys to the `env` argument, one can also pass in the keyword `:pipe` to get streams for standard IO of the subprocess that can be read from and written to. The returned value `proc` has the fields :in, :out, :err, :return-code, and the additional field :pid on unix-like platforms. Use `(os/proc-wait proc)` to rejoin the subprocess or `(os/proc-kill proc)`.
Community Examples / source
cfunction (os/stat path &opt tab|key)
Gets information about a file or directory. Returns a table if the second argument is a keyword, returns only that information from stat. If the file or directory does not exist, returns nil. The keys are:

* :dev - the device that the file is on

* :mode - the type of file, one of :file, :directory, :block, :character, :fifo, :socket, :link, or :other

* :int-permissions - A Unix permission integer like 8r744

* :permissions - A Unix permission string like "rwxr--r--"

* :uid - File uid

* :gid - File gid

* :nlink - number of links to file

* :rdev - Real device of file. 0 on Windows

* :size - size of file in bytes

* :blocks - number of blocks in file. 0 on Windows

* :blocksize - size of blocks in file. 0 on Windows

* :accessed - timestamp when file last accessed

* :changed - timestamp when file last changed (permissions changed)

* :modified - timestamp when file last modified (content changed)
Community Examples / source
cfunction (os/symlink oldpath newpath)
Create a symlink from oldpath to newpath, returning nil. Same as `(os/link oldpath newpath true)`.
Community Examples / source
cfunction (os/time )
Get the current time expressed as the number of whole seconds since January 1, 1970, the Unix epoch. Returns a real number.
Community Examples / source
cfunction (os/touch path &opt actime modtime)
Update the access time and modification times for a file. By default, sets times to the current time.
Community Examples / source
cfunction (os/umask mask)
Set a new umask, returns the old umask.
Community Examples / source
cfunction (os/which )
Check the current operating system. Returns one of:

* :windows

* :mingw

* :cygwin

* :macos

* :web - Web assembly (emscripten)

* :linux

* :freebsd

* :openbsd

* :netbsd

* :posix - A POSIX compatible system (default)

May also return a custom keyword specified at build time.
Community Examples / source
function (pairs x)
Get the key-value pairs of an associative data structure.
Community Examples / source
function (parse str)
Parse a string and return the first value. For complex parsing, such as for a repl with error handling,
use the parser api.
Community Examples / source
function (parse-all str)
Parse a string and return all parsed values. For complex parsing, such as for a repl with error handling,
use the parser api.
Community Examples / source
cfunction (parser/byte parser b)
Input a single byte `b` into the parser byte stream. Returns the parser.
Community Examples / source
cfunction (parser/clone p)
Creates a deep clone of a parser that is identical to the input parser. This cloned parser can be used to continue parsing from a good checkpoint if parsing later fails. Returns a new parser.
Community Examples / source
cfunction (parser/consume parser bytes &opt index)
Input bytes into the parser and parse them. Will not throw errors if there is a parse error. Starts at the byte index given by `index`. Returns the number of bytes read.
Community Examples / source
cfunction (parser/eof parser)
Indicate to the parser that the end of file was reached. This puts the parser in the :dead state.
Community Examples / source
cfunction (parser/error parser)
If the parser is in the error state, returns the message associated with that error. Otherwise, returns nil. Also flushes the parser state and parser queue, so be sure to handle everything in the queue before calling `parser/error`.
Community Examples / source
cfunction (parser/flush parser)
Clears the parser state and parse queue. Can be used to reset the parser if an error was encountered. Does not reset the line and column counter, so to begin parsing in a new context, create a new parser.
Community Examples / source
cfunction (parser/has-more parser)
Check if the parser has more values in the value queue.
Community Examples / source
cfunction (parser/insert parser value)
Insert a value into the parser. This means that the parser state can be manipulated in between chunks of bytes. This would allow a user to add extra elements to arrays and tuples, for example. Returns the parser.
Community Examples / source
cfunction (parser/new )
Creates and returns a new parser object. Parsers are state machines that can receive bytes and generate a stream of values.
Community Examples / source
cfunction (parser/produce parser &opt wrap)
Dequeue the next value in the parse queue. Will return nil if no parsed values are in the queue, otherwise will dequeue the next value. If `wrap` is truthy, will return a 1-element tuple that wraps the result. This tuple can be used for source-mapping purposes.
Community Examples / source
cfunction (parser/state parser &opt key)
Returns a representation of the internal state of the parser. If a key is passed, only that information about the state is returned. Allowed keys are:

* :delimiters - Each byte in the string represents a nested data structure. For example, if the parser state is '(["', then the parser is in the middle of parsing a string inside of square brackets inside parentheses. Can be used to augment a REPL prompt.

* :frames - Each table in the array represents a 'frame' in the parser state. Frames contain information about the start of the expression being parsed as well as the type of that expression and some type-specific information.
Community Examples / source
cfunction (parser/status parser)
Gets the current status of the parser state machine. The status will be one of:

* :pending - a value is being parsed.

* :error - a parsing error was encountered.

* :root - the parser can either read more values or safely terminate.
Community Examples / source
cfunction (parser/where parser &opt line col)
Returns the current line number and column of the parser's internal state. If line is provided, the current line number of the parser is first set to that value. If column is also provided, the current column number of the parser is also first set to that value.
Community Examples / source
function (partial f & more)
Partial function application.
Community Examples / source
function (partition n ind)
Partition an indexed data structure `ind` into tuples
of size `n`. Returns a new array.
Community Examples / source
function (partition-by f ind)
Partition elements of a sequential data structure by a representative function `f`. Partitions
split when `(f x)` changes values when iterating to the next element `x` of `ind`. Returns a new array
of arrays.
Community Examples / source
cfunction (peg/compile peg)
Compiles a peg source data structure into a <core/peg>. This will speed up matching if the same peg will be used multiple times. Will also use `(dyn :peg-grammar)` to suppliment the grammar of the peg for otherwise undefined peg keywords.
Community Examples / source
cfunction (peg/find peg text &opt start & args)
Find first index where the peg matches in text. Returns an integer, or nil if not found.
Community Examples / source
cfunction (peg/find-all peg text &opt start & args)
Find all indexes where the peg matches in text. Returns an array of integers.
Community Examples / source
cfunction (peg/match peg text &opt start & args)
Match a Parsing Expression Grammar to a byte string and return an array of captured values. Returns nil if text does not match the language defined by peg. The syntax of PEGs is documented on the Janet website.
Community Examples / source
cfunction (peg/replace peg repl text &opt start & args)
Replace first match of peg in text with repl, returning a new buffer. The peg does not need to make captures to do replacement. If no matches are found, returns the input string in a new buffer.
Community Examples / source
cfunction (peg/replace-all peg repl text &opt start & args)
Replace all matches of peg in text with repl, returning a new buffer. The peg does not need to make captures to do replacement.
Community Examples / source
function (pos? x)
Check if x is greater than 0.
Community Examples / source
function (postwalk f form)
Do a post-order traversal of a data structure and call `(f x)`
on every visitation.
Community Examples / source
function (pp x)
Pretty-print to stdout or `(dyn *out*)`. The format string used is `(dyn *pretty-format* "%q")`.
Community Examples / source
function (prewalk f form)
Similar to `postwalk`, but do pre-order traversal.
Community Examples / source
cfunction (prin & xs)
Same as `print`, but does not add trailing newline.
Community Examples / source
cfunction (prinf fmt & xs)
Like `printf` but with no trailing newline.
Community Examples / source
cfunction (print & xs)
Print values to the console (standard out). Value are converted to strings if they are not already. After printing all values, a newline character is printed. Use the value of `(dyn :out stdout)` to determine what to push characters to. Expects `(dyn :out stdout)` to be either a core/file or a buffer. Returns nil.
Community Examples / source
cfunction (printf fmt & xs)
Prints output formatted as if with `(string/format fmt ;xs)` to `(dyn :out stdout)` with a trailing newline.
Community Examples / source
function (product xs)
Returns the product of xs. If xs is empty, returns 1.
Example:
(product []) # -> 1
(product @[1 2 3]) # -> 6
(product [0 1 2 3]) # -> 0
(product (range 1 10)) # -> 362880

# Product over byte values [0-255] in a string
(product "hello") # -> 1.35996e+10

# Product over values in a table or struct
(sum {:a 1 :b 2 :c 4}) # -> 8
Community Examples / source
macro (prompt tag & body)
Set up a checkpoint that can be returned to. `tag` should be a value
that is used in a `return` statement, like a keyword.
Community Examples / source
function (propagate x fiber)
Propagate a signal from a fiber to the current fiber. The resulting stack trace from the current fiber will include frames from fiber. If fiber is in a state that can be resumed, resuming the current fiber will first resume fiber. This function can be used to re-raise an error without losing the original stack trace.
Community Examples /
macro (protect & body)
Evaluate expressions, while capturing any errors. Evaluates to a tuple
of two elements. The first element is true if successful, false if an
error, and the second is the return value or error.
Community Examples / source
function (put ds key value)
Associate a key with a value in any mutable associative data structure. Indexed data structures (arrays and buffers) only accept non-negative integer keys, and will expand if an out of bounds value is provided. In an array, extra space will be filled with nils, and in a buffer, extra space will be filled with 0 bytes. In a table, putting a key that is contained in the table prototype will hide the association defined by the prototype, but will not mutate the prototype table. Putting a value nil into a table will remove the key from the table. Returns the data structure ds.
Community Examples /
function (put-in ds ks v)
Put a value into a nested data structure `ds`. Looks into `ds` via
a sequence of keys. Missing data structures will be replaced with tables. Returns
the modified, original data structure.
Community Examples / source
function (quit &opt value)
Tries to exit from the current repl or run-context. Does not always exit the application.
Works by setting the :exit dynamic binding to true. Passing a non-nil `value` here will cause the outer
run-context to return that value.
Community Examples / source
function (range & args)
Create an array of values [start, end) with a given step.
With one argument, returns a range [0, end). With two arguments, returns
a range [start, end). With three, returns a range with optional step size.
Example:
(range 10) # -> @[0 1 2 3 4  6 7 8 9]
(range 5 10) # -> @[5 6 7 8 9]
(range 5 10 2) # -> @[5 7 9]
(range 5 11 2) # -> @[5 7 9]
(range 10 0 -1) # -> @[10 9 8 7 6 5 4 3 2 1]
Community Examples / source
function (reduce f init ind)
Reduce, also know as fold-left in many languages, transforms
an indexed type (array, tuple) with a function to produce a value by applying `f` to
each element in order. `f` is a function of 2 arguments, `(f accum el)`, where
`accum` is the initial value and `el` is the next value in the indexed type `ind`.
`f` returns a value that will be used as `accum` in the next call to `f`. `reduce`
returns the value of the final call to `f`.
Community Examples / source
function (reduce2 f ind)
The 2-argument version of `reduce` that does not take an initialization value.
Instead, the first element of the array is used for initialization.
Community Examples / source
macro (repeat n & body)
Evaluate body n times. If n is negative, body will be evaluated 0 times. Evaluates to nil.
Community Examples / source
function (repl &opt chunks onsignal env parser read)
Run a repl. The first parameter is an optional function to call to
get a chunk of source code that should return nil for end of file.
The second parameter is a function that is called when a signal is
caught. One can provide an optional environment table to run
the repl in, as well as an optional parser or read function to pass
to `run-context`.
Community Examples / source
function (require path & args)
Require a module with the given name. Will search all of the paths in
`module/paths`. Returns the new environment
returned from compiling and running the file.
Community Examples / source
function (resume fiber &opt x)
Resume a new or suspended fiber and optionally pass in a value to the fiber that will be returned to the last yield in the case of a pending fiber, or the argument to the dispatch function in the case of a new fiber. Returns either the return result of the fiber's dispatch function, or the value from the next yield call in fiber.
Community Examples /
function (return to &opt value)
Return to a prompt point.
Community Examples / source
function (reverse t)
Reverses the order of the elements in a given array or tuple and returns
a new array. If a string or buffer is provided, returns an array of its
byte values, reversed.
Example:
(reverse [1 2 3]) # -> @[3 2 1]
(reverse "abcdef") # -> @[102 101 100 99 98 97]
(reverse :abc) # -> @[99 98 97]

Community Examples / source
function (reverse! t)
Reverses the order of the elements in a given array or buffer and returns it
mutated.
Community Examples / source
table root-env
The root environment used to create environments with (make-env).
Community Examples /
function (run-context opts)
Run a context. This evaluates expressions in an environment,
and encapsulates the parsing, compilation, and evaluation.
Returns `(in environment :exit-value environment)` when complete.
`opts` is a table or struct of options. The options are as follows:

 * `:chunks` -- callback to read into a buffer - default is getline

 * `:on-parse-error` -- callback when parsing fails - default is bad-parse

 * `:env` -- the environment to compile against - default is the current env

 * `:source` -- source path for better errors (use keywords for non-paths) - default
 is :<anonymous>

 * `:on-compile-error` -- callback when compilation fails - default is bad-compile

 * `:on-compile-warning` -- callback for any linting error - default is warn-compile

 * `:evaluator` -- callback that executes thunks. Signature is (evaluator thunk source
    env where)

  * `:on-status` -- callback when a value is evaluated - default is debug/stacktrace.

  * `:fiber-flags` -- what flags to wrap the compilation fiber with. Default is :ia.

  * `:expander` -- an optional function that is called on each top level form before
    being compiled.

  * `:parser` -- provide a custom parser that implements the same interface as Janet's
    built-in parser.

  * `:read` -- optional function to get the next form, called like `(read env source)`.
    Overrides all parsing.
Community Examples / source
cfunction (sandbox & forbidden-capabilities)
Disable feature sets to prevent the interpreter from using certain system resources. Once a feature is disabled, there is no way to re-enable it. Capabilities can be:

* :all - disallow all (except IO to stdout, stderr, and stdin)
* :env - disallow reading and write env variables
* :ffi - disallow FFI (recommended if disabling anything else)
* :fs - disallow access to the file system
* :fs-read - disallow read access to the file system
* :fs-temp - disallow creating temporary files
* :fs-write - disallow write access to the file system
* :hrtime - disallow high-resolution timers
* :modules - disallow load dynamic modules (natives)
* :net - disallow network access
* :net-connect - disallow making outbound network connections
* :net-listen - disallow accepting inbound network connections
* :sandbox - disallow calling this function
* :subprocess - disallow running subprocesses
Community Examples / source
cfunction (scan-number str &opt base)
Parse a number from a byte sequence and return that number, either an integer or a real. The number must be in the same format as numbers in janet source code. Will return nil on an invalid number. Optionally provide a base - if a base is provided, no radix specifier is expected at the beginning of the number.
Community Examples / source
macro (seq head & body)
Similar to `loop`, but accumulates the loop body into an array and returns that.
See `loop` for details.
Example:
(seq [x :range [0 5]] (* 2 x)) # -> @[0 2 4 6 8]
Community Examples / source
cfunction (setdyn key value)
Set a dynamic binding. Returns value.
Community Examples / source
macro (short-fn arg &opt name)
Shorthand for `fn`. Arguments are given as `$n`, where `n` is the 0-indexed
argument of the function. `$` is also an alias for the first (index 0) argument.
The `$&` symbol will make the anonymous function variadic if it appears in the
body of the function, and can be combined with positional arguments.

Example usage:

 (short-fn (+ $ $)) # A function that doubles its arguments.
 (short-fn (string $0 $1)) # accepting multiple args.
 |(+ $ $) # use pipe reader macro for terse function literals.
   |(+ $&)  # variadic functions
Community Examples / source
cfunction (signal what x)
Raise a signal with payload x. 
Community Examples / source
cfunction (slice x &opt start end)
Extract a sub-range of an indexed data structure or byte sequence.
Example:
(slice @[1 2 3]) # -> (1 2 3) (a new array!)
(slice @[:a :b :c] 1) # -> (:b :c)
(slice [:a :b :c :d :e] 2 4) # -> (:c :d)
(slice [:a :b :d :d :e] 2 -1) # -> (:c :d :e)
(slice [:a :b :d :d :e] 2 -2) # -> (:c :d)
(slice [:a :b :d :d :e] 2 -4) # -> ()
(slice [:a :b :d :d :e] 2 -10) # -> error: range error
(slice "abcdefg" 0 2) # -> "ab"
(slice @"abcdefg" 0 2) # -> "ab"

Community Examples / source
function (slurp path)
Read all data from a file with name `path` and then close the file.
Community Examples / source
function (some pred xs)
Returns nil if all `xs` are false or nil, otherwise returns the result of the
first truthy predicate, `(pred x)`.
Community Examples / source
function (sort ind &opt before?)
Sorts `ind` in-place, and returns it. Uses quick-sort and is not a stable sort.
If a `before?` comparator function is provided, sorts elements using that,
otherwise uses `<`.
Community Examples / source
function (sort-by f ind)
Sorts `ind` in-place by calling a function `f` on each element and
comparing the result with `<`.
Community Examples / source
function (sorted ind &opt before?)
Returns a new sorted array without modifying the old one.
If a `before?` comparator function is provided, sorts elements using that,
otherwise uses `<`.
Community Examples / source
function (sorted-by f ind)
Returns a new sorted array that compares elements by invoking
a function `f` on each element and comparing the result with `<`.
Community Examples / source
function (spit path contents &opt mode)
Write `contents` to a file at `path`. Can optionally append to the file.
Community Examples / source
core/file stderr
The standard error file.
Community Examples / source
core/file stdin
The standard input file.
Community Examples / source
core/file stdout
The standard output file.
Community Examples / source
cfunction (string & xs)
Creates a string by concatenating the elements of `xs` together. If an element is not a byte sequence, it is converted to bytes via `describe`. Returns the new string.
Community Examples / source
cfunction (string/ascii-lower str)
Returns a new string where all bytes are replaced with the lowercase version of themselves in ASCII. Does only a very simple case check, meaning no unicode support.
Community Examples / source
cfunction (string/ascii-upper str)
Returns a new string where all bytes are replaced with the uppercase version of themselves in ASCII. Does only a very simple case check, meaning no unicode support.
Community Examples / source
cfunction (string/bytes str)
Returns a tuple of integers that are the byte values of the string.
Community Examples / source
cfunction (string/check-set set str)
Checks that the string `str` only contains bytes that appear in the string `set`. Returns true if all bytes in `str` appear in `set`, false if some bytes in `str` do not appear in `set`.
Community Examples / source
cfunction (string/find patt str &opt start-index)
Searches for the first instance of pattern `patt` in string `str`. Returns the index of the first character in `patt` if found, otherwise returns nil.
Community Examples / source
cfunction (string/find-all patt str &opt start-index)
Searches for all instances of pattern `patt` in string `str`. Returns an array of all indices of found patterns. Overlapping instances of the pattern are counted individually, meaning a byte in `str` may contribute to multiple found patterns.
Community Examples / source
cfunction (string/format format & values)
Similar to C's `snprintf`, but specialized for operating with Janet values. Returns a new string.
Community Examples / source
cfunction (string/from-bytes & byte-vals)
Creates a string from integer parameters with byte values. All integers will be coerced to the range of 1 byte 0-255.
Community Examples / source
cfunction (string/has-prefix? pfx str)
Tests whether `str` starts with `pfx`.
Community Examples / source
cfunction (string/has-suffix? sfx str)
Tests whether `str` ends with `sfx`.
Community Examples / source
cfunction (string/join parts &opt sep)
Joins an array of strings into one string, optionally separated by a separator string `sep`.
Community Examples / source
cfunction (string/repeat bytes n)
Returns a string that is `n` copies of `bytes` concatenated.
Community Examples / source
cfunction (string/replace patt subst str)
Replace the first occurrence of `patt` with `subst` in the string `str`. Will return the new string if `patt` is found, otherwise returns `str`.
Community Examples / source
cfunction (string/replace-all patt subst str)
Replace all instances of `patt` with `subst` in the string `str`. Overlapping matches will not be counted, only the first match in such a span will be replaced. Will return the new string if `patt` is found, otherwise returns `str`.
Community Examples / source
cfunction (string/reverse str)
Returns a string that is the reversed version of `str`.
Community Examples / source
cfunction (string/slice bytes &opt start end)
Returns a substring from a byte sequence. The substring is from index `start` inclusive to index `end`, exclusive. All indexing is from 0. `start` and `end` can also be negative to indicate indexing from the end of the string. Note that index -1 is synonymous with index `(length bytes)` to allow a full negative slice range. 
Community Examples / source
cfunction (string/split delim str &opt start limit)
Splits a string `str` with delimiter `delim` and returns an array of substrings. The substrings will not contain the delimiter `delim`. If `delim` is not found, the returned array will have one element. Will start searching for `delim` at the index `start` (if provided), and return up to a maximum of `limit` results (if provided).
Community Examples / source
cfunction (string/trim str &opt set)
Trim leading and trailing whitespace from a byte sequence. If the argument `set` is provided, consider only characters in `set` to be whitespace.
Community Examples / source
cfunction (string/triml str &opt set)
Trim leading whitespace from a byte sequence. If the argument `set` is provided, consider only characters in `set` to be whitespace.
Community Examples / source
cfunction (string/trimr str &opt set)
Trim trailing whitespace from a byte sequence. If the argument `set` is provided, consider only characters in `set` to be whitespace.
Community Examples / source
function (string? x)
Check if x is a string.
Community Examples / source
cfunction (struct & kvs)
Create a new struct from a sequence of key value pairs. kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has an odd number of elements, an error will be thrown. Returns the new struct.
Community Examples / source
cfunction (struct/getproto st)
Return the prototype of a struct, or nil if it doesn't have one.
Community Examples / source
cfunction (struct/proto-flatten st)
Convert a struct with prototypes to a struct with no prototypes by merging all key value pairs from recursive prototypes into one new struct.
Community Examples / source
cfunction (struct/to-table st &opt recursive)
Convert a struct to a table. If recursive is true, also convert the table's prototypes into the new struct's prototypes as well.
Community Examples / source
cfunction (struct/with-proto proto & kvs)
Create a structure, as with the usual struct constructor but set the struct prototype as well.
Community Examples / source
function (struct? x)
Check if x a struct.
Community Examples / source
function (sum xs)
Returns the sum of xs. If xs is empty, returns 0.
Example:
(sum []) # -> 0
(sum @[1]) # -> 1
(sum (range 100)) # -> 4950

# Sum over bytes values [0-255] in a string
(sum "hello") # -> 532

# Sum over values in a table or struct
(sum {:a 1 :b 2 :c 4}) # -> 7
Community Examples / source
cfunction (symbol & xs)
Creates a symbol by concatenating the elements of `xs` together. If an element is not a byte sequence, it is converted to bytes via `describe`. Returns the new symbol.
Community Examples / source
cfunction (symbol/slice bytes &opt start end)
Same as string/slice, but returns a symbol.
Community Examples / source
function (symbol? x)
Check if x is a symbol.
Community Examples / source
cfunction (table & kvs)
Creates a new table from a variadic number of keys and values. kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has an odd number of elements, an error will be thrown. Returns the new table.
Community Examples / source
cfunction (table/clear tab)
Remove all key-value pairs in a table and return the modified table `tab`.
Community Examples / source
cfunction (table/clone tab)
Create a copy of a table. Updates to the new table will not change the old table, and vice versa.
Community Examples / source
cfunction (table/getproto tab)
Get the prototype table of a table. Returns nil if the table has no prototype, otherwise returns the prototype.
Community Examples / source
cfunction (table/new capacity)
Creates a new empty table with pre-allocated memory for `capacity` entries. This means that if one knows the number of entries going into a table on creation, extra memory allocation can be avoided. Returns the new table.
Community Examples / source
cfunction (table/proto-flatten tab)
Create a new table that is the result of merging all prototypes into a new table.
Community Examples / source
cfunction (table/rawget tab key)
Gets a value from a table `tab` without looking at the prototype table. If `tab` does not contain the key directly, the function will return nil without checking the prototype. Returns the value in the table.
Community Examples / source
cfunction (table/setproto tab proto)
Set the prototype of a table. Returns the original table `tab`.
Community Examples / source
cfunction (table/to-struct tab)
Convert a table to a struct. Returns a new struct. This function does not take into account prototype tables.
Community Examples / source
function (table? x)
Check if x a table.
Community Examples / source
macro (tabseq head key-body & value-body)
Similar to `loop`, but accumulates key value pairs into a table.
See `loop` for details.
Community Examples / source
function (take n ind)
Take the first n elements of a fiber, indexed or bytes type. Returns a new array, tuple or string, respectively.
Community Examples / source
function (take-until pred ind)
Same as `(take-while (complement pred) ind)`.
Community Examples / source
function (take-while pred ind)
Given a predicate, take only elements from a fiber, indexed, or bytes type that satisfy
the predicate, and abort on first failure. Returns a new array, tuple, or string, respectively.
Community Examples / source
macro (toggle value)
Set a value to its boolean inverse. Same as `(set value (not value))`.
Community Examples / source
cfunction (trace func)
Enable tracing on a function. Returns the function.
Community Examples / source
macro (tracev x)
Print to stderr a value and a description of the form that produced that value.
Evaluates to x.
Community Examples / source
function (true? x)
Check if x is true.
Community Examples / source
function (truthy? x)
Check if x is truthy.
Community Examples / source
macro (try body catch)
Try something and catch errors. `body` is any expression,
and `catch` should be a form, the first element of which is a tuple. This tuple
should contain a binding for errors and an optional binding for
the fiber wrapping the body. Returns the result of `body` if no error,
or the result of `catch` if an error.
Community Examples / source
cfunction (tuple & items)
Creates a new tuple that contains items. Returns the new tuple.
Community Examples / source
cfunction (tuple/brackets & xs)
Creates a new bracketed tuple containing the elements xs.
Community Examples / source
cfunction (tuple/setmap tup line column)
Set the sourcemap metadata on a tuple. line and column indicate should be integers.
Community Examples / source
cfunction (tuple/slice arrtup [,start=0 [,end=(length arrtup)
]])

Take a sub-sequence of an array or tuple from index `start` inclusive to index `end` exclusive. If `start` or `end` are not provided, they default to 0 and the length of `arrtup`, respectively. `start` and `end` can also be negative to indicate indexing from the end of the input. Note that index -1 is synonymous with index `(length arrtup)` to allow a full negative slice range. Returns the new tuple.
Community Examples / source
cfunction (tuple/sourcemap tup)
Returns the sourcemap metadata attached to a tuple, which is another tuple (line, column).
Community Examples / source
cfunction (tuple/type tup)
Checks how the tuple was constructed. Will return the keyword :brackets if the tuple was parsed with brackets, and :parens otherwise. The two types of tuples will behave the same most of the time, but will print differently and be treated differently by the compiler.
Community Examples / source
function (tuple? x)
Check if x is a tuple.
Community Examples / source
cfunction (type x)
Returns the type of `x` as a keyword. `x` is one of:

* :nil

* :boolean

* :number

* :array

* :tuple

* :table

* :struct

* :string

* :buffer

* :symbol

* :keyword

* :function

* :cfunction

* :fiber

or another keyword for an abstract type.
Example:
(type nil) # -> :nil
(type true) # -> :boolean
(type false) # -> :boolean
(type 1) # -> :number
(type :key) # -> :keyword
(type (int/s64 "100")) # -> :core/s64
Community Examples / source
macro (unless condition & body)
Shorthand for `(when (not condition) ;body)`. 
Community Examples / source
cfunction (unmarshal buffer &opt lookup)
Unmarshal a value from a buffer. An optional lookup table can be provided to allow for aliases to be resolved. Returns the value unmarshalled from the buffer.
Community Examples / source
cfunction (untrace func)
Disables tracing on a function. Returns the function.
Community Examples / source
function (update ds key func & args)
For a given key in data structure `ds`, replace its corresponding value with the
result of calling `func` on that value. If `args` are provided, they will be passed
along to `func` as well. Returns `ds`, updated.
Community Examples / source
function (update-in ds ks f & args)
Update a value in a nested data structure `ds`. Looks into `ds` via a sequence of keys,
and replaces the value found there with `f` applied to that value.
Missing data structures will be replaced with tables. Returns
the modified, original data structure.
Community Examples / source
macro (use & modules)
Similar to `import`, but imported bindings are not prefixed with a module
identifier. Can also import multiple modules in one shot.
Community Examples / source
function (values x)
Get the values of an associative data structure.
Community Examples / source
macro (var- name & more)
Define a private var that will not be exported.
Community Examples / source
macro (varfn name & body)
Create a function that can be rebound. `varfn` has the same signature
as `defn`, but defines functions in the environment as vars. If a var `name`
already exists in the environment, it is rebound to the new function. Returns
a function.
Community Examples / source
function (varglobal name init)
Dynamically create a global var.
Community Examples / source
function (walk f form)
Iterate over the values in ast and apply `f`
to them. Collect the results in a data structure. If ast is not a
table, struct, array, or tuple,
returns form.
Community Examples / source
function (warn-compile msg level where &opt line col)
Default handler for a compile warning.
Community Examples / source
macro (when condition & body)
Evaluates the body when the condition is true. Otherwise returns nil.
Community Examples / source
macro (when-let bindings & body)
Same as `(if-let bindings (do ;body))`.
Community Examples / source
macro (when-with [binding ctor dtor] & body)
Similar to with, but if binding is false or nil, returns
nil without evaluating the body. Otherwise, the same as `with`.
Community Examples / source
macro (with [binding ctor dtor] & body)
Evaluate `body` with some resource, which will be automatically cleaned up
if there is an error in `body`. `binding` is bound to the expression `ctor`, and
`dtor` is a function or callable that is passed the binding. If no destructor
(`dtor`) is given, will call :close on the resource.
Example:
# Print all of poetry.txt, and close the file when done,
# even when there is an error.
(with [f (file/open "poetry.txt")]
  (print (:read f :all)))
Community Examples / source
macro (with-dyns bindings & body)
Run a block of code in a new fiber that has some
dynamic bindings set. The fiber will not mask errors
or signals, but the dynamic bindings will be properly
unset, as dynamic bindings are fiber-local.
Community Examples / source
macro (with-syms syms & body)
Evaluates `body` with each symbol in `syms` bound to a generated, unique symbol.
Community Examples / source
macro (with-vars vars & body)
Evaluates `body` with each var in `vars` temporarily bound. Similar signature to
`let`, but each binding must be a var.
Community Examples / source
cfunction (xprin to & xs)
Print to a file or other value explicitly (no dynamic bindings). The value to print to is the first argument, and is otherwise the same as `prin`. Returns nil.
Community Examples / source
cfunction (xprinf to fmt & xs)
Like `prinf` but prints to an explicit file or value `to`. Returns nil.
Community Examples / source
cfunction (xprint to & xs)
Print to a file or other value explicitly (no dynamic bindings) with a trailing newline character. The value to print to is the first argument, and is otherwise the same as `print`. Returns nil.
Community Examples / source
cfunction (xprintf to fmt & xs)
Like `printf` but prints to an explicit file or value `to`. Returns nil.
Community Examples / source
function (yield &opt x)
Yield a value to a parent fiber. When a fiber yields, its execution is paused until another thread resumes it. The fiber will then resume, and the last yield call will return the value that was passed to resume.
Community Examples /
function (zero? x)
Check if x is zero.
Community Examples / source
function (zipcoll ks vs)
Creates a table from two arrays/tuples.
Returns a new table.
Community Examples / source