Skip to content

Latest commit

 

History

History
432 lines (311 loc) · 7.12 KB

File metadata and controls

432 lines (311 loc) · 7.12 KB

← Architecture | Built-ins | Examples | Contributing →


Built-in Functions

Reference for all built-in functions available in Carv.

Output

print(...args)

Prints arguments to stdout, space-separated, without a trailing newline.

print("hello", "world");  // hello world
print(1, 2, 3);           // 1 2 3

println(...args)

Prints arguments to stdout, space-separated, with a trailing newline.

Type Conversion

str(value) -> string

Convert any value to its string representation.

str(42)        // "42"
str(true)      // "true"
str([1,2,3])   // "[1, 2, 3]"

int(value) -> int

Convert to integer. Works with floats and booleans.

int(3.14)   // 3
int(true)   // 1
int(false)  // 0

float(value) -> float

Convert to float.

float(42)  // 42.0

type_of(value) -> string

Get the type of a value as a string.

type_of(42)        // "INTEGER"
type_of("hello")   // "STRING"
type_of([1,2,3])   // "ARRAY"

Collections

len(collection) -> int

Get length of string or array.

len("hello")     // 5
len([1, 2, 3])   // 3

push(array, item) -> array

Return new array with item appended.

let a = [1, 2];
let b = push(a, 3);  // [1, 2, 3]
// a is still [1, 2]

head(array) -> any

Get first element of array.

head([1, 2, 3])  // 1
head([])         // nil

tail(array) -> array

Get all elements except the first.

tail([1, 2, 3])  // [2, 3]
tail([1])        // []

Maps

keys(map) -> array

Get all keys from a map.

let m = {"a": 1, "b": 2};
keys(m)  // ["a", "b"]

values(map) -> array

Get all values from a map.

let m = {"a": 1, "b": 2};
values(m)  // [1, 2]

has_key(map, key) -> bool

Check if key exists in map.

let m = {"a": 1};
has_key(m, "a")  // true
has_key(m, "b")  // false

set(map, key, value) -> map

Return new map with key set to value.

let m = {"a": 1};
let m2 = set(m, "b", 2);  // {"a": 1, "b": 2}

delete(map, key) -> map

Return new map with key removed.

let m = {"a": 1, "b": 2};
let m2 = delete(m, "a");  // {"b": 2}

Strings

split(str, separator) -> array

Split string into array.

split("a,b,c", ",")  // ["a", "b", "c"]

join(array, separator) -> string

Join array into string.

join(["a", "b", "c"], "-")  // "a-b-c"

trim(str) -> string

Remove leading/trailing whitespace.

trim("  hello  ")  // "hello"

substr(str, start, end?) -> string

Get substring. End is optional.

substr("hello", 0, 2)  // "he"
substr("hello", 2)     // "llo"

contains(str, substr) -> bool

Check if string contains substring.

contains("hello", "ell")  // true

starts_with(str, prefix) -> bool

Check if string starts with prefix.

starts_with("hello", "he")  // true

ends_with(str, suffix) -> bool

Check if string ends with suffix.

ends_with("hello", "lo")  // true

replace(str, old, new) -> string

Replace all occurrences.

replace("hello", "l", "L")  // "heLLo"

index_of(str, substr) -> int

Find index of substring. Returns -1 if not found.

index_of("hello", "l")   // 2
index_of("hello", "x")   // -1

to_upper(str) -> string

Convert to uppercase.

to_upper("hello")  // "HELLO"

to_lower(str) -> string

Convert to lowercase.

to_lower("HELLO")  // "hello"

ord(char) -> int

Get ASCII code of character.

ord('A')     // 65
ord("A")     // 65 (takes first char)

chr(int) -> char

Get character from ASCII code.

chr(65)  // 'A'

char_at(str, index) -> char

Get character at index.

char_at("hello", 1)  // 'e'

Parsing

parse_int(str) -> int

Parse a string as an integer.

parse_int("42")    // 42
parse_int("-10")   // -10

parse_float(str) -> float

Parse a string as a float.

parse_float("3.14")   // 3.14
parse_float("2.0")    // 2

Process & Environment

args() -> array

Get command-line arguments passed to the script.

let a = args();
print(a);   // ["arg1", "arg2", ...]

exec(command, ...args) -> int

Run an external command. Returns the exit code.

let code = exec("echo", "hello");  // prints "hello", returns 0

exec_output(command, ...args) -> Result

Run an external command and capture output. Returns Ok(stdout) or Err(stderr).

let result = exec_output("echo", "hello");
match result {
    Ok(out) => print(trim(out)),
    Err(e) => print("failed: " + e),
}

getenv(key) -> string

Get an environment variable. Returns empty string if not set.

let home = getenv("HOME");

setenv(key, value)

Set an environment variable.

setenv("MY_VAR", "hello");

File I/O

read_file(path) -> string

Read entire file contents.

let content = read_file("data.txt");

write_file(path, content)

Write string to file.

write_file("out.txt", "hello");

append_file(path, content)

Append string to file. Creates the file if it doesn't exist.

append_file("log.txt", "new line\n");

file_exists(path) -> bool

Check if file exists.

if file_exists("config.txt") {
    // ...
}

mkdir(path)

Create a directory (and parent directories).

mkdir("build/output");

remove_file(path)

Delete a file.

remove_file("old.txt");

rename_file(old_path, new_path)

Rename or move a file.

rename_file("old.txt", "new.txt");

read_dir(path) -> array

Read directory entries and return sorted file/directory names.

let entries = read_dir(".");
println(entries);

cwd() -> string

Get current working directory.

println(cwd());

Networking (TCP)

Use these via the built-in net or web module:

require "net" as net;

net and web currently expose the same low-level TCP primitives.

tcp_listen(host, port) -> int

Create a TCP listener and return a listener handle.

let listener = net.tcp_listen("127.0.0.1", 8080);

tcp_accept(listener) -> int

Accept one incoming TCP connection and return a connection handle.

let conn = net.tcp_accept(listener);

tcp_read(conn, max_bytes) -> string

Read up to max_bytes bytes from a TCP connection.

let request = net.tcp_read(conn, 4096);

tcp_write(conn, data) -> int

Write string data to a TCP connection. Returns number of bytes written.

let wrote = net.tcp_write(conn, "hello");

tcp_close(handle) -> bool

Close a listener or connection handle.

net.tcp_close(conn);
net.tcp_close(listener);

Control Flow

exit(code?)

Exit program with optional status code.

exit();    // exit with 0
exit(1);   // exit with 1

panic(message)

Crash with error message.

panic("something went wrong");

← Architecture | Built-ins | Examples | Contributing →