Built-in Functions

Complete reference for all built-in functions.

Output Functions

FunctionDescription
say($value)Print value with newline
print($value)Print value without newline
warn($msg)Print warning to stderr
die($msg)Print error and exit

String Functions

FunctionDescription
strlen($str)Return string length
substr($str, $start, $len)Extract substring
index($str, $substr)Find first occurrence, -1 if not found
rindex($str, $substr)Find last occurrence
uc($str)Convert to uppercase
lc($str)Convert to lowercase
ucfirst($str)Uppercase first character
lcfirst($str)Lowercase first character
trim($str)Remove leading/trailing whitespace
split($sep, $str)Split string into array
join($sep, @arr)Join array into string
chr($code)Character from ASCII code
ord($char)ASCII code from character
sprintf($fmt, ...)Formatted string (like C sprintf)
stringify($val)Convert value to string

Examples

my str $s = "  Hello World  ";
say(strlen($s));           # 15
say(trim($s));             # "Hello World"
say(substr($s, 2, 5));    # "Hello"
say(uc($s));               # "  HELLO WORLD  "
say(index($s, "World"));  # 8

my array @parts = split(" ", trim($s));
say(join("-", @parts));   # "Hello-World"

Array Functions

FunctionDescription
len(@arr)Return array length
scalar(@arr)Return array length (alias for len)
push(@arr, $val)Add element to end
pop(@arr)Remove and return last element
shift(@arr)Remove and return first element
unshift(@arr, $val)Add element to beginning
reverse(@arr)Reverse array elements in place
sort(@arr)Return sorted array
splice(@arr, $off, $len)Remove/replace elements

Array Memory Management

FunctionDescription
sys::array_capacity(@arr)Get current allocated capacity
sys::array_reserve(@arr, $n)Ensure capacity for at least $n elements
sys::array_shrink(@arr)Shrink capacity to match length

Pre-allocating Arrays

For performance, pre-allocate arrays when you know the approximate size:

my array @data[1000];  # Pre-allocate for 1000 elements
for (my int $i = 0; $i < 1000; $i++) {
    push(@data, $i);  # No reallocation needed
}

Hash Functions

FunctionDescription
keys(%hash)Return array of keys
values(%hash)Return array of values
exists(%hash, $key)Check if key exists (returns 1/0)
delete(%hash, $key)Remove key-value pair
each(%hash)Return next key-value pair
sys::hash_default_capacity($n)Set default capacity for new hashes

Pre-allocating Hashes

Pre-allocate hashes when you know the approximate size:

my hash %cache[500];  # Pre-allocate for ~500 entries

# Or set default for all new hashes:
sys::hash_default_capacity(1000);

Hashes automatically resize for O(1) average lookup time.

Type Functions

FunctionDescription
int($val)Convert to integer
num($val)Convert to number
defined($val)Check if value is defined
ref($val)Return reference type or empty string
typeof($val)Return type as string
bless(\%h, $class)Associate hash ref with class

File I/O Functions

FunctionDescription
slurp($path)Read entire file as string
spew($path, $data)Write string to file
sys::open($path, $mode)Open file, return fd
sys::read($fd, $len)Read bytes from fd
sys::write($fd, $data)Write bytes to fd
sys::close($fd)Close file descriptor
sys::seek($fd, $pos, $whence)Seek in file
sys::tell($fd)Get current position
sys::eof($fd)Check if at end of file
sys::flush($fd)Flush file buffer

Math Functions (math::)

FunctionDescription
math::abs($n)Absolute value
math::floor($n)Round down
math::ceil($n)Round up
math::round($n)Round to nearest
math::sqrt($n)Square root
math::pow($base, $exp)Power
math::sin($n)Sine
math::cos($n)Cosine
math::tan($n)Tangent
math::log($n)Natural logarithm
math::log10($n)Base-10 logarithm
math::exp($n)e^n
math::rand()Random number 0-1
math::srand($seed)Seed random generator

System Functions (sys::)

Process Control

FunctionDescription
sys::exit($code)Exit with status code
sys::fork()Fork process
sys::exec($cmd, @args)Execute command
sys::system($cmd)Run shell command
sys::wait()Wait for child process
sys::waitpid($pid)Wait for specific process
sys::getpid()Get process ID
sys::getppid()Get parent process ID
sys::kill($pid, $sig)Send signal to process

Environment

FunctionDescription
sys::getenv($name)Get environment variable
sys::setenv($name, $val)Set environment variable
sys::getcwd()Get current directory
sys::chdir($path)Change directory

File System

FunctionDescription
sys::stat($path)Get file info
sys::mkdir($path)Create directory
sys::rmdir($path)Remove directory
sys::unlink($path)Delete file
sys::rename($old, $new)Rename file
sys::readdir($path)List directory
sys::is_dir($path)Check if directory
sys::is_file($path)Check if regular file
sys::realpath($path)Get absolute path
sys::dirname($path)Get directory part
sys::basename($path)Get filename part
sys::glob($pattern)Glob pattern matching

Time

FunctionDescription
sys::time()Unix timestamp
sys::localtime($ts)Convert to local time hash
sys::gmtime($ts)Convert to GMT hash
sys::sleep($secs)Sleep for seconds
sys::usleep($usecs)Sleep for microseconds

Networking

FunctionDescription
sys::socket_server($port)Create TCP server
sys::socket_accept($fd)Accept connection
sys::socket_connect($host, $port)Connect to server
sys::gethostbyname($host)Resolve hostname
sys::gethostbyname_all($host)Resolve hostname (all addresses)
sys::gethostname()Get local hostname
sys::getaddrinfo($host, $port)Advanced address resolution

SSL/TLS (ssl::)

Secure socket connections via OpenSSL. Build with: cd lib/ssl && make

FunctionDescription
ssl::connect($host, $port)Connect to TLS server
ssl::read($conn, $len)Read from TLS connection
ssl::write($conn, $data)Write to TLS connection
ssl::close($conn)Close TLS connection
ssl::http_get($host, $port, $path)Simple HTTPS GET request

SSL Example

my int $conn = ssl::connect("example.com", 443);
ssl::write($conn, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
my str $response = ssl::read($conn, 4096);
ssl::close($conn);

# Or use the convenience function:
my str $page = ssl::http_get("example.com", 443, "/");

Signals

FunctionDescription
sys::signal($sig, \&handler)Set signal handler
sys::signal($sig, "IGNORE")Ignore signal
sys::signal($sig, "DEFAULT")Reset to default

Dynamic Loading (FFI)

FunctionDescription
sys::dl_open($lib)Load shared library
sys::dl_sym($handle, $name)Get symbol address
sys::dl_call_sv($fn, @args)Call Strada function (returns StradaValue)
sys::dl_call_int_sv($fn, @args)Call Strada function (returns int)
sys::dl_call_str_sv($fn, @args)Call Strada function (returns str)
sys::dl_call_void_sv($fn, @args)Call Strada function (void return)
sys::dl_call_version($fn)Get library version string
sys::dl_close($handle)Unload library

FFI Example

# Load a Strada shared library
my int $lib = sys::dl_open("./mylib.so");
my int $fn = sys::dl_sym($lib, "my_function");
my scalar $result = sys::dl_call_sv($fn, [$arg1, $arg2]);

import_lib

For cleaner library imports, use import_lib:

use lib "lib";
import_lib "JSON";

# Functions are now available with namespace syntax:
my str $json = JSON::encode(\%data);
my hash %data = JSON::decode($json);

Shared Library Compilation

Compile Strada programs as shared libraries:

./strada --shared mylib.strada   # Creates mylib.so

C Interop (__C__ Blocks)

Embed raw C code directly in Strada programs using __C__ blocks:

Top-Level Blocks

For includes, globals, and C helper functions:

__C__ {
    #include <math.h>
    #include <openssl/ssl.h>

    static SSL_CTX *g_ctx = NULL;

    static int helper(int a, int b) {
        return a + b;
    }
}

Statement-Level Blocks

Inline C code inside functions with access to Strada variables:

func my_sqrt(num $x) num {
    __C__ {
        double val = strada_to_num(x);
        return strada_new_num(sqrt(val));
    }
}

Key C Functions

FunctionDescription
strada_to_int(sv)Extract int64_t from StradaValue*
strada_to_num(sv)Extract double from StradaValue*
strada_to_str(sv)Extract string (caller must free!)
strada_new_int(i)Create StradaValue* from int64_t
strada_new_num(n)Create StradaValue* from double
strada_new_str(s)Create StradaValue* from string
&strada_undefReturn undef value

Opaque Handle Pattern

Store C pointers in Strada int variables (64-bit):

func open_connection(str $host) int {
    __C__ {
        char *h = strada_to_str(host);
        SSL *conn = connect_ssl(h);
        free(h);
        // Store pointer as int
        return strada_new_int((int64_t)(intptr_t)conn);
    }
}

func close_connection(int $handle) void {
    __C__ {
        // Retrieve pointer from int
        SSL *conn = (SSL*)(intptr_t)strada_to_int(handle);
        SSL_free(conn);
        return &strada_undef;
    }
}

JSON Functions

FunctionDescription
json_encode($val)Convert to JSON string
json_decode($str)Parse JSON string

Miscellaneous

FunctionDescription
dump($val)Debug print value structure
caller()Get caller information
eval($code)Evaluate Strada code string
$obj->isa($class)Check if object is instance of class
$obj->can($method)Check if object has method

Compiler Flags

The Strada compiler (stradac) and wrapper (strada) support these flags:

FlagDescription
-r, --runCompile and run immediately
-c, --keep-cKeep generated .c file
-g, --debugInclude debug symbols
-p, --profileEnable function profiling
-w, --warningsShow compiler warnings
-t, --timingShow compilation phase timing
--sharedCompile as shared library (.so)
-L <path>Add library search path (high priority)
-LL <path>Add library search path (low priority)

Examples

# Compile and run
./strada -r program.strada

# Compile with debugging
./strada -g program.strada

# Compile with profiling
./strada -p program.strada
./program  # Prints profiling report on exit

# Check for warnings
./strada -w program.strada

# Create shared library
./strada --shared mylib.strada  # Creates mylib.so