Modules. #

Modules have their own namespace and contain accessible static symbols. By default, importing another Cyber script returns a module with its declared symbols.

Importing. #

Import declarations create a local alias to the module referenced by the import specifier. The Cyber CLI comes with some builtin modules like math and test. If the specifier does not refer to a builtin module, it looks for a Cyber script file relative to the current script’s directory. An embedder can integrate their own module loader.

import t 'test'
t.eq(123, 123)

-- Imports are static declarations so they can be anywhere in the script.
import m 'math'
print m.cos(0)

-- Loading another Cyber script.
import foo ''
print foo.myFunc()
print foo.myVar

A Cyber script that is imported doesn’t evaluate its main block. Only static declarations are effectively loaded. If there is code in the main block, it will skip evaluation. In the following, only the print statement in the is evaluated.

import a ''

import ''
var foo: 123
print foo         -- Statement is ignored.

var bar: 321
print bar         -- Statement is ignored.

You can have circular imports in Cyber. In the following example, and import each other without any problems.

import foo ''

func printB():


import main ''

func printA():

func printC():
    print 'done'

Static variable declarations from imports can have circular references. Read more about this in Static Variables.

Modules can also be destructured using the following syntax:

import { cos, pi } 'math'
print cos(pi)

Exporting. #

All static declarations are exported when the script’s module is loaded.

func foo():         -- Exported static function.
    print 123

var bar: 234        -- Exported static variable.

type Thing object:  -- Exported type.
    a float

The annotation @hide provides a hint to editors that the static symbol should not appear in the auto-complete. Despite this, the symbol is still reachable.

Builtin Modules. #

Builtin modules are the bare minimum that comes with Cyber. The embeddable library contains these modules and nothing more. They include:

  • builtins: Cyber related functions and commonly used utilities.
  • math: Math constants and functions.

Incomplete: The docs for builtin modules are not completely up-to-date. They will be auto generated in the future.

builtins. #

The builtins module contains functions related to Cyber and common utilities. It is automatically imported into each script’s namespace.

Sample usage:

-- `print` and `typeid` are available without imports.
print 'hello'
var id = typeid('my str')
print id
arrayFill(val any, n int) ListCreates a list with initial capacity of n and values set to val. If the value is an object, it is shallow copied n times.
boolean(val any) booleanConverts a value to either true or false.
copy(val any) anyCopies a primitive value or creates a shallow copy of an object value.
dump(val any) nonePrints the result of toCyon on a value.
error(e (enum | symbol)) errorCreate an error from an enum or symbol.
evalJS(val string) noneEvals JS from the host environment. This is only available in a web WASM build of Cyber.
float(val any) floatCasts or converts the value to a float. Panics if type conversion fails.
int(val any) intConverts a value to an 32-bit integer.
isAlpha(val int) booleanReturns whether a rune is an alphabetic letter.
isDigit(val int) booleanReturns whether a rune is a digit.
must(val any) any | noreturnIf val is an error, panic(val) is invoked. Otherwise, val is returned.
panic(e symbol) noreturnStop execution in the current fiber and starts unwinding the call stack. See Unexpected Errors.
parseCyber(src any) mapParses Cyber source string into structured map object. Currently, only metadata about static declarations is made available but this will be extended to include an AST.
parseCyon(src any) anyParses a CYON string into a value.
performGC() mapRuns the garbage collector once to detect reference cycles and abandoned objects. Returns the statistics of the run in a map value.
pointer(val any) pointerConverts a int to a pointer value, or casts to a pointer. This is usually used with FFI.
print(s string) nonePrints a value. The host determines how it is printed.
rawstring(str string) rawstringConverts a string to a rawstring.
runestr(val int) stringConverts a rune to a string.
string(val any) stringConverts a value to a string.
toCyon(val any) stringEncodes a value to CYON string.
typeof(any) metatypeReturns the value’s type as a metatype object.
typesym(any) symbolReturns the value’s type as one of the predefined symbols: #float, #int, #boolean, #object, #list, #map, #string, #rawstring, #function, #fiber, #pointer, #symbol, #metatype, #none, #error

math. #

The math module contains commonly used math constants and functions.

Sample usage:

import m 'math'

var r = 10
print(m.pi * r^2)
efloatEuler’s number and the base of natural logarithms; approximately 2.718.
log10efloatBase-10 logarithm of E; approximately 0.434.
log2efloatBase-2 logarithm of E; approximately 1.443.
ln10floatNatural logarithm of 10; approximately 2.303.
ln2floatNatural logarithm of 2; approximately 0.693.
nanfloatNot a number. Note that nan == nan, however, if a nan came from an arithmetic operation, the comparison is undefined (it may be true or false, so it is not reliable).
neginffloatNegative infinity.
pifloatRatio of a circle’s circumference to its diameter; approximately 3.14159.
sqrt1_2floatSquare root of ½; approximately 0.707.
sqrt2floatSquare root of 2; approximately 1.414.
abs(float) floatReturns the absolute value of x.
acos(float) floatReturns the arccosine of x.
acosh(float) floatReturns the hyperbolic arccosine of x.
asin(float) floatReturns the arcsine of x.
asinh(float) floatReturns the hyperbolic arcsine of a number.
atan(float) floatReturns the arctangent of x.
atan2(float, float) floatReturns the arctangent of the quotient of its arguments.
atanh(float) floatReturns the hyperbolic arctangent of x.
cbrt(float) floatReturns the cube root of x.
ceil(float) floatReturns the smallest integer greater than or equal to x.
clz32(float) floatReturns the number of leading zero bits of the 32-bit integer x.
cos(float) floatReturns the cosine of x.
cosh(float) floatReturns the hyperbolic cosine of x.
exp(float) floatReturns e^x, where x is the argument, and e is Euler’s number (2.718…, the base of the natural logarithm).
expm1(float) floatReturns subtracting 1 from exp(x).
floor(float) floatReturns the largest integer less than or equal to x.
hypot(float, float) floatReturns the square root of the sum of squares of its arguments.
isNaN(float) boolReturns whether x is not a number.
ln(float) floatReturns the natural logarithm (㏒e; also, ㏑) of x.
log(float, float) floatReturns the logarithm of y with base x.
log10(float) floatReturns the base-10 logarithm of x.
log1p(float) floatReturns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x.
log2(float) floatReturns the base-2 logarithm of x.
max(float, float) floatReturns the largest of two numbers.
min(float, float) floatReturns the smallest of two numbers.
mul32(float, float) floatReturns the result of the 32-bit integer multiplication of x and y. Integer overflow is allowed.
pow(float, float) floatReturns base x to the exponent power y (that is, x^y).
random() floatReturns a pseudo-random number between 0 and 1.
round(float) floatReturns the value of the number x rounded to the nearest integer.
sign(float) floatReturns the sign of the x, indicating whether x is positive, negative, or zero.
sin(float) floatReturns the sine of x.
sinh(float) floatReturns the hyperbolic sine of x.
sqrt(float) floatReturns the positive square root of x.
tan(float) floatReturns the tangent of x.
tanh(float) floatReturns the hyperbolic tangent of x.
trunc(float) floatReturns the integer portion of x, removing any fractional digits.

Std Modules. #

Std modules come with Cyber’s CLI. They include:

  • os: System level functions.
  • test: Utilities for testing.

Incomplete: The docs for std modules are not completely up-to-date. They will be auto generated in the future.

os. #

Cyber’s os module contains system level functions. It’s still undecided as to how much should be included here so it’s incomplete. You can still access os and libc functions yourself using Cyber’s FFI or embedding API.

Sample usage:

import os 'os'

var map = os.getEnvAll()
for map each k, v:
    print '{k} -> {v}'
cpustringThe current cpu arch’s tag name.
endian#little, #bigThe current arch’s endianness.
stderrFileStandard error file descriptor.
stdinFileStandard input file descriptor.
stdoutFileStandard output file descriptor.
systemstringThe current operating system’s tag name.
vecBitSizeintDefault SIMD vector bit size.
access(path any, mode (#read | #write | #readWrite)) true | errorAttempts to access a file at the given path with the #read, #write, or #readWrite mode. Return true or an error.
args() List<string | rawstring>Returns the command line arguments as a list. Each argument is validated and returned as a UTF-8 string or rawstring if the validation failed.
bindLib(path any, decls [](CFunc|CStruct)) Object | MapCalls bindLib(path, decls, {}).
bindLib(path any, decls [](CFunc|CStruct), config: BindLibConfig) Object | MapCreates an FFI binding to a dynamic library and it’s symbols. By default, an anonymous object is returned with the C-functions binded as the object’s methods. If config contains genMap: true, a Map is returned instead with C-functions binded as function values.
cacheUrl(url string) stringReturns the path of a locally cached file of url. If no such file exists locally, it’s fetched from url.
copyFile(srcPath any, dstPath any) none | errorCopies a file to a destination path.
createDir(path any) true | errorCreates the directory at path. Returns true if successful.
createFile(path any, truncate boolean) File | errorCreates and opens the file at path. If truncate is true, an existing file will be truncated.
cstr(any) pointerReturns a null terminated C string.
cwd() stringReturns the current working directory.
dirName(path any) string | noneReturns the given path with its last component removed.
execCmd(args []string) Map{ out, err, exited }Runs a shell command and returns the stdout/stderr.
exePath() stringReturns the current executable’s path.
exit(status int) noreturnExits the program with a status code.
fetchUrl(url string) rawstringFetches the contents at url using the HTTP GET request method.
free(ptr pointer) noneFrees the memory located at ptr.
fromCstr(pointer) rawstringReturns a rawstring from a null terminated C string.
getEnv(key any) string | noneReturns an environment value by key.
getEnvAll() MapReturns all environment entries as a Map.
getInput() rawstringReads stdin until a new line is reached. This is intended to read user input from the command line. For bulk reads from stdin, use os.stdin.
malloc(size int) pointerAllocates size bytes of memory and returns a pointer.
milliTime() floatReturn the calendar timestamp, in milliseconds, relative to UTC 1970-01-01.
openDir(path any) Dir | errorInvokes openDir(path, false).
openDir(path any, iterable boolean) Dir | errorOpens a directory at the given path. iterable indicates that the directory’s entries can be iterated.
openFile(path any, mode (#read | #write | #readWrite)) File | errorOpens a file at the given path with the #read, #write, or #readWrite mode.
parseArgs(options list[ArgOption]) mapGiven expected ArgOptions, returns a map of the options and a rest entry which contains the non-option arguments.
readAll() rawstringReads stdin to the EOF as a rawstring.
readFile(path string) rawstringReads the file contents into a rawstring value.
realPath(path any) string | errorReturns the absolute path of the given path.
removeDir(path any) true | errorRemoves an empty directory at path. Returns true if successful.
removeFile(path any) true | errorRemoves the file at path. Returns true if successful.
setEnv(key any, value any) noneSets an environment value by key.
sleep(ms float) nonePauses the current thread for given milliseconds.
unsetEnv(key any) noneRemoves an environment value by key.
writeFile(path string, contents string) noneWrites a string value to a file.

type File #

close() noneCloses the file handle. File ops invoked afterwards will return error.Closed.
read(n float) rawstringReads at most n bytes as a rawstring. n must be at least 1. A result with length 0 indicates the end of file was reached.
readToEnd() rawstringReads to the end of the file and returns the content as a rawstring.
seek(pos float) noneSeeks the read/write position to pos bytes from the start. Negative pos is invalid.
seekFromCur(pos float) noneSeeks the read/write position by pos bytes from the current position.
seekFromEnd(pos float) noneSeeks the read/write position by pos bytes from the end. Positive pos is invalid.
stat() MapReturns info about the file as a Map.
streamLines() Iterable<rawstring>Equivalent to streamLines(4096).
streamLines(bufSize float) Iterable<rawstring>Returns an iterable that streams lines ending in \n, \r, \r\n, or the EOF. The lines returned include the new line character(s). A buffer size of bufSize bytes is allocated for reading. If \r is found at the end of the read buffer, the line is returned instead of waiting to see if the next read has a connecting \n.
write(data (string | rawstring)) floatWrites a string or rawstring at the current file position. The number of bytes written is returned.

type Dir #

iterator() Iterator<DirEntry> | errorReturns a new iterator over the directory entries. If this directory was not opened with the iterable flag, error.NotAllowed is returned instead.
stat() MapReturns info about the file as a Map.
walk() Iterator<DirWalkEntry> | errorReturns a new iterator over the directory recursive entries. If this directory was not opened with the iterable flag, error.NotAllowed is returned instead.

map DirEntry #

'name' -> rawstringThe name of the file or directory.
'type' -> #file | #dir | #unknownThe type of the entry.

map DirWalkEntry #

'name' -> rawstringThe name of the file or directory.
'path' -> rawstringThe path of the file or directory relative to the walker’s root directory.
'type' -> #file | #dir | #unknownThe type of the entry.

map ArgOption #

'name' -> stringThe name of the option to match excluding the hyphen prefix. eg. -path
'type' -> metatype(string | float | boolean)Parse as given value type.
'default' -> anyOptional: Default value if option is missing. none is used if this is not provided.

test. #

The test module contains utilities for testing.

Sample usage:

import t 'test'

var a = 123 + 321
t.eq(a, 444)
eq(a any, b any) true | errorReturns whether two values are equal. Returns error.AssertError if types do not match up.
eqList(a any, b any) true | errorReturns true if two lists have the same size and the elements are equal as if eq was called on those corresponding elements.
eqNear(a any, b any) true | errorReturns two numbers are near each other within epsilon 1e-5.