Skip to main content

Built-in Functions

Uddin-Lang provides a comprehensive set of built-in functions to help you build powerful applications efficiently.

Type Conversion Functions

FunctionDescriptionExampleReturn Type
str(value)Convert to stringstr(42)"42"string
int(value)Convert to integerint("42")42int
float(value)Convert to floatfloat("3.14")3.14float
bool(value)Convert to booleanbool(1)truebool
char(value)Convert to characterchar(65)"A"string
rune(value)Convert to Unicode runerune("A")65int
type(value)Get type nametype(42)"int"string
typeof(value)Get detailed type infotypeof([1,2,3])"array[int]"string

String Functions

Basic String Operations

FunctionDescriptionExampleReturn Type
len(string)String lengthlen("hello")5int
substr(string, start, length)Extract substringsubstr("hello", 1, 3)"ell"string
split(string, delimiter)Split stringsplit("a,b,c", ",")["a","b","c"]array
join(array, delimiter)Join array to stringjoin(["a","b"], ",")"a,b"string
trim(string)Remove whitespacetrim(" hello ")"hello"string
replace(string, old, new)Replace substringreplace("hello", "l", "x")"hexxo"string

String Case Functions

FunctionDescriptionExampleReturn Type
upper(string)Convert to uppercaseupper("hello")"HELLO"string
lower(string)Convert to lowercaselower("HELLO")"hello"string

String Search Functions

FunctionDescriptionExampleReturn Type
contains(string, substring)Check if containscontains("hello", "ell")truebool
starts_with(string, prefix)Check prefixstarts_with("hello", "he")truebool
ends_with(string, suffix)Check suffixends_with("hello", "lo")truebool

Array Functions

Core Array Functions

FunctionDescriptionExampleReturn Type
len(array)Array lengthlen([1,2,3])3int
append(array, items...)Add itemsappend([1,2], 3, 4)[1,2,3,4]array
slice(array, start, end)Extract sliceslice([1,2,3,4], 1, 3)[2,3]array
sort(array)Sort in placesort([3,1,2])[1,2,3]array
range(n) or range(start, stop)Create rangerange(3)[0,1,2]
range(1, 4)[1,2,3]
array
find(array, value)Find indexfind([1,2,3], 2)1int
contains(array, value)Check membershipcontains([1,2,3], 2)truebool

Functional Programming Methods

FunctionDescriptionExample
map(array, function)Transform each elementmap([1,2,3], fun(x): return x*2 end)[2,4,6]
filter(array, function)Filter elements by conditionfilter([1,2,3,4], fun(x): return x%2==0 end)[2,4]
reduce(array, function, init)Reduce to single valuereduce([1,2,3], fun(a,x): return a+x end, 0)6
reverse(array)Reverse array in-placereverse([1,2,3]) modifies to [3,2,1]
push(array, element)Add element to endpush([1,2], 3) modifies to [1,2,3]
pop(array)Remove and return last elementpop([1,2,3])3, array becomes [1,2]
shift(array)Remove and return first elementshift([1,2,3])1, array becomes [2,3]
unshift(array, element)Add element to beginningunshift([2,3], 1) modifies to [1,2,3]
index_of(array, element)Find first index of elementindex_of([1,2,3,2], 2)1
last_index_of(array, element)Find last index of elementlast_index_of([1,2,3,2], 2)3

Data Structures

Set (Unique Collection)

FunctionDescriptionExample
set_new()Create new empty setmy_set = set_new()
set_add(set, elem)Add element (ignores duplicates)set_add(my_set, 1)
set_has(set, elem)Check if element existsset_has(my_set, 1)true
set_remove(set, elem)Remove elementset_remove(my_set, 1)true
set_size(set)Get number of elementsset_size(my_set)3
set_to_array(set)Convert set to arrayset_to_array(my_set)[1,2,3]

Stack (LIFO - Last In, First Out)

FunctionDescriptionExample
stack_new()Create new empty stackmy_stack = stack_new()
stack_push(stack, elem)Add element to topstack_push(my_stack, "item")
stack_pop(stack)Remove and return top elementstack_pop(my_stack)"item"
stack_peek(stack)View top element without removingstack_peek(my_stack)"item"
stack_size(stack)Get number of elementsstack_size(my_stack)3
stack_empty(stack)Check if stack is emptystack_empty(my_stack)false

Queue (FIFO - First In, First Out)

FunctionDescriptionExample
queue_new()Create new empty queuemy_queue = queue_new()
queue_enqueue(queue, elem)Add element to backqueue_enqueue(my_queue, "task")
queue_dequeue(queue)Remove and return front elementqueue_dequeue(my_queue)"task"
queue_front(queue)View front element without removingqueue_front(my_queue)"task"
queue_size(queue)Get number of elementsqueue_size(my_queue)3
queue_empty(queue)Check if queue is emptyqueue_empty(my_queue)false

Math Functions

Basic Math Operations

FunctionDescriptionExampleReturn Type
abs(x)Absolute valueabs(-5)5int/float
max(a, b, ...)Maximum valuemax(1, 5, 3)5int/float
min(a, b, ...)Minimum valuemin(1, 5, 3)1int/float
pow(base, exp)Power functionpow(2, 3)8int/float
sqrt(x)Square rootsqrt(16)4.0float
cbrt(x)Cube rootcbrt(27)3.0float

Rounding Functions

FunctionDescriptionExampleReturn Type
round(x)Round to nearest integerround(3.7)4int
round(x, n)Round to n decimal placesround(3.14159, 2)3.14float
floor(x)Round down (floor)floor(3.7)3int
ceil(x)Round up (ceiling)ceil(3.2)4int
trunc(x)Truncate decimal parttrunc(3.7)3int

Trigonometric Functions

FunctionDescriptionExampleReturn Type
sin(x)Sine (radians)sin(PI/2)1.0float
cos(x)Cosine (radians)cos(0)1.0float
tan(x)Tangent (radians)tan(PI/4)1.0float
asin(x)Arc sine (returns radians)asin(1)1.5708float
acos(x)Arc cosine (returns radians)acos(1)0.0float
atan(x)Arc tangent (returns radians)atan(1)0.7854float
atan2(y, x)Arc tangent of y/xatan2(1, 1)0.7854float

Hyperbolic Functions

FunctionDescriptionExampleReturn Type
sinh(x)Hyperbolic sinesinh(1.0)1.175float
cosh(x)Hyperbolic cosinecosh(1.0)1.543float
tanh(x)Hyperbolic tangenttanh(1.0)0.762float

Logarithmic Functions

FunctionDescriptionExampleReturn Type
log(x)Natural logarithm (ln)log(E)1.0float
log10(x)Base-10 logarithmlog10(100)2.0float
log2(x)Base-2 logarithmlog2(8)3.0float
logb(x, base)Logarithm with custom baselogb(125, 5)3.0float
exp(x)Exponential function (e^x)exp(1)2.718...float
exp2(x)Base-2 exponential (2^x)exp2(3)8.0float

Statistical Functions

FunctionDescriptionExampleReturn Type
sum(array)Sum of array elementssum([1, 2, 3, 4])10int/float
mean(array)Arithmetic mean (average)mean([1, 2, 3, 4])2.5float
median(array)Median valuemedian([1, 2, 3, 4, 5])3.0float
mode(array)Most frequent valuemode([1, 2, 2, 3])2any
std_dev(array)Standard deviationstd_dev([1, 2, 3, 4])1.29float
variance(array)Variancevariance([1, 2, 3, 4])1.67float

Number Theory Functions

FunctionDescriptionExampleReturn Type
gcd(a, b)Greatest common divisorgcd(12, 8)4int
lcm(a, b)Least common multiplelcm(12, 8)24int
factorial(n)Factorial (n!)factorial(5)120int
fibonacci(n)Nth Fibonacci numberfibonacci(7)13int
is_prime(n)Check if number is primeis_prime(17)truebool
prime_factors(n)List of prime factorsprime_factors(12)[2,2,3]array

Random Number Functions

FunctionDescriptionExampleReturn Type
random()Random float between 0 and 1random()0.7234float
random_int(min, max)Random integer in rangerandom_int(1, 10)7int
random_float(min, max)Random float in rangerandom_float(1.0, 2.0)1.45float
random_choice(array)Random element from arrayrandom_choice([1,2,3])2any
shuffle(array)Shuffle array in placeshuffle([1,2,3])[3,1,2]array
seed_random(seed)Set random seedseed_random(42)null

Mathematical Constants

ConstantDescriptionValue
PIPi (π)3.14159265359
EEuler's number (e)2.71828182846
TAUTau (2π)6.28318530718
PHIGolden ratio (φ)1.61803398875
LN2Natural logarithm of 20.69314718056
LN10Natural logarithm of 102.30258509299
SQRT2Square root of 21.41421356237
SQRT3Square root of 31.73205080757

I/O Functions

FunctionDescriptionExampleReturn Type
print(values...)Print to consoleprint("Hello", "World")void
input(prompt)Read user inputname = input("Enter name: ")string
read_file(path)Read file contentcontent = read_file("data.txt")string
write_file(path, content)Write to filewrite_file("out.txt", "Hello")bool

File System Operations

File Operations

FunctionDescriptionExampleReturn Type
read_file(path)Read file contentcontent = read_file("data.txt")string
write_file(path, content)Write content to filewrite_file("output.txt", "Hello World")bool
file_exists(path)Check if file/directory existsfile_exists("config.json")truebool
file_size(path)Get file size in bytesfile_size("data.txt")1024int
file_modified(path)Get last modification timefile_modified("log.txt")"2024-01-15"string
file_permissions(path)Get file permissionsfile_permissions("script.sh")"755"string
copy_file(source, destination)Copy file to new locationcopy_file("src.txt", "backup.txt")bool
move_file(source, destination)Move/rename filemove_file("old.txt", "new.txt")bool
delete_file(path)Delete filedelete_file("temp.txt")bool

Directory Operations

FunctionDescriptionExampleReturn Type
mkdir(path)Create directorymkdir("logs")bool
rmdir(path)Remove empty directoryrmdir("temp")bool
list_dir(path)List directory contentslist_dir(".")["file1", "dir1"]array
getcwd()Get current working directorygetcwd()"/home/user/project"string
chdir(path)Change working directorychdir("/tmp")bool

Path Operations

FunctionDescriptionExampleReturn Type
path_join(parts...)Join path componentspath_join("home", "user", "file.txt")string
path_dirname(path)Get directory namepath_dirname("/home/user/file.txt")string
path_basename(path)Get base filenamepath_basename("/home/user/file.txt")string
path_ext(path)Get file extensionpath_ext("document.pdf")".pdf"string

JSON Functions

FunctionDescriptionExample
json_parse(json_string)Parse JSON string to Uddin-Lang valuedata = json_parse('{"name": "John", "age": 30}')
json_stringify(value)Convert Uddin-Lang value to JSON stringjson_str = json_stringify({name: "Alice", age: 25})

JSON Type Mapping

JSON TypeUddin-Lang TypeExample
objectmap[string]Value{"key": "value"}{key: "value"}
array[]Value[1, 2, 3][1, 2, 3]
stringstring"hello""hello"
numberint or float644242, 3.143.14
booleanbooltruetrue
nullnullnullnull

XML Processing

FunctionDescriptionExample
xml_parse(xml_string)Parse XML string to Uddin-Lang valuedata = xml_parse('<person><name>John</name></person>')
xml_stringify(value)Convert Uddin-Lang value to XML stringxml_str = xml_stringify({person: {name: "Alice", age: "25"}})

XML Structure Mapping

XML FeatureUddin-Lang RepresentationExample
Root ElementMap key<root>...</root>{"root": {...}}
Child ElementsMap properties<name>John</name>{"name": "John"}
Attributes@attributes object<item id="1">{"@attributes": {"id": "1"}}
Text ContentString value<title>Book</title>{"title": "Book"}
Multiple ElementsArray<item>1</item><item>2</item>[1, 2]

Networking Functions

HTTP Client Functions

FunctionDescriptionExample
http_get(url)HTTP GET requesthttp_get("https://api.example.com/data")
http_post(url, data)HTTP POST requesthttp_post("https://api.example.com", data)
http_put(url, data)HTTP PUT requesthttp_put("https://api.example.com/1", data)
http_delete(url)HTTP DELETE requesthttp_delete("https://api.example.com/1")
http_request(method, url, data)Generic HTTP requesthttp_request("PATCH", url, data)

HTTP Server Functions

FunctionDescriptionExample
http_server_start(port, server_id?)Start HTTP server on specified portserver = http_server_start(8080, "main")
http_server_stop(server_id?)Stop HTTP serverhttp_server_stop("main")
http_server_route(method, path, handler, server_id?)Register route handlerhttp_server_route("GET", "/api", my_handler, "main")
http_response(res, status, headers?, body?)Send HTTP responsehttp_response(res, 200, {"Content-Type": "text/plain"}, "Hello")

Network Utilities

FunctionDescriptionExample
net_resolve(hostname)Resolve hostname to IP addressesnet_resolve("google.com")["142.250.191.14"]
net_ping(host, port, timeout)Test connectivity to host:portnet_ping("google.com", 80, 3000){"success": true, "time": 45}

TCP Functions

FunctionDescriptionExample
tcp_connect(host, port)Create TCP client connectionconn = tcp_connect("localhost", 8080)
tcp_listen(port)Create TCP server listenerlistener = tcp_listen(8080)
tcp_accept(listener)Accept incoming TCP connectionclient = tcp_accept(listener)
tcp_read(connection)Read data from TCP connectiondata = tcp_read(conn)
tcp_write(connection, data)Write data to TCP connectiontcp_write(conn, "Hello Server!")
tcp_close(connection)Close TCP connection/listenertcp_close(conn)

UDP Functions

FunctionDescriptionExample
udp_connect(host, port)Create UDP client connectionconn = udp_connect("localhost", 8080)
udp_listen(port)Create UDP server listenerlistener = udp_listen(8080)
udp_read(connection)Read data from UDP connectiondata = udp_read(conn)
udp_write(connection, data)Write data to UDP connectionudp_write(conn, "Hello Server!")
udp_close(connection)Close UDP connection/listenerudp_close(conn)

Utility Functions

FunctionDescriptionExampleReturn Type
sign(x)Sign of number (-1, 0, 1)sign(-5)-1int
clamp(x, min, max)Clamp value to rangeclamp(15, 1, 10)10int/float
lerp(a, b, t)Linear interpolationlerp(0, 10, 0.5)5.0float
degrees(radians)Convert radians to degreesdegrees(PI)180.0float
radians(degrees)Convert degrees to radiansradians(180)3.14159float
is_nan(x)Check if value is NaNis_nan(0.0/0.0)truebool
is_infinite(x)Check if value is infiniteis_infinite(1.0/0.0)truebool
date_now()Current timestampdate_now()"2025-06-26T14:30:00Z"string
time_now()Current Unix timestamp in millisecondstime_now()1640995445123int
date_format(date, fmt)Format datedate_format(date_now(), "YYYY-MM-DD")string
date_parse(date_str, layout)Parse date stringdate_parse("2023-01-01", "2006-01-02")int
date_format_new(timestamp, layout)Format timestamp with layoutdate_format_new(time_now(), "2006-01-02 15:04:05")string
date_add(timestamp, duration)Add duration to timestampdate_add(time_now(), "24h")int
date_subtract(timestamp, duration)Subtract duration from timestampdate_subtract(time_now(), "1h30m")int
date_diff(timestamp1, timestamp2)Calculate difference between timestampsdate_diff(time2, time1)int
date_between(timestamp, start, end)Check if timestamp is between two datesdate_between(now, start, end)bool
date_compare(timestamp1, timestamp2)Compare two timestampsdate_compare(time1, time2)int

Regular Expression Functions

FunctionDescriptionExampleReturn Type
is_regex_match(pattern, text)Check if text matches regex patternis_regex_match("^[0-9]+$", "123")truebool
regex_match(text, pattern)Check if text matches regex patternregex_match("hello@example.com", email_pattern)bool
regex_find(text, pattern)Find first match of regex patternregex_find("Phone: 123-456-7890", "[0-9-]+")"123-456-7890"string
regex_find_all(text, pattern)Find all matches of regex patternregex_find_all(text, email_pattern)array
regex_replace(text, pattern, replacement)Replace regex matchesregex_replace("hello world", "world", "universe")string
regex_split(text, pattern)Split text by regex patternregex_split("a,b;c", "[,;]")["a", "b", "c"]array

Database Functions

Connection Management

FunctionDescriptionExampleReturn Type
db_connect(driver, host, port, database, username, password)Connect to databasedb_connect("postgres", "localhost", 5432, "mydb", "user", "pass")object
db_connect_with_pool(driver, host, port, database, username, password, pool_config)Connect with connection pooldb_connect_with_pool("postgres", "localhost", 5432, "mydb", "user", "pass", pool_config)object
db_configure_pool(connection, max_open, max_idle, max_lifetime)Configure connection pooldb_configure_pool(conn, 20, 10, 3600)object
db_close(connection)Close database connectiondb_close(conn)void

Query Operations

FunctionDescriptionExampleReturn Type
db_query(connection, query, params...)Execute SELECT querydb_query(conn, "SELECT * FROM users WHERE id = $1", 123)object
db_execute(connection, query, params...)Execute INSERT/UPDATE/DELETEdb_execute(conn, "INSERT INTO users (name) VALUES ($1)", "John")object
db_execute_batch(connection, operations)Execute multiple operations in batchdb_execute_batch(conn, operations_array)object

Asynchronous Operations

FunctionDescriptionExampleReturn Type
db_execute_async(connection, query, params...)Execute query asynchronouslydb_execute_async(conn, "SELECT * FROM large_table")object
db_get_async_status(operation_id)Get status of async operationdb_get_async_status("op_123")object
db_cancel_async(operation_id)Cancel async operationdb_cancel_async("op_123")object
db_list_async_operations()List all async operationsdb_list_async_operations()object
db_cleanup_async_operations()Clean up completed async operationsdb_cleanup_async_operations()object

Real-time Streaming

FunctionDescriptionExampleReturn Type
stream_tables(connection, table_name, callback)Start real-time streaming for single tablestream_tables(conn, "users", on_change)void
stream_tables(connection, table_names, callback)Start real-time streaming for multiple tablesstream_tables(conn, ["users", "orders"], on_multi_change)void
stream_tables(connection, table_name, callback, columns)Stream with column selectionstream_tables(conn, "users", on_change, ["id", "name"])void
db_stop_stream(streamer_id)Stop real-time streamingdb_stop_stream("streamer_123")void

Database Function Examples

Basic Connection and Query

// Connect to PostgreSQL
conn_result = db_connect("postgres", "localhost", 5432, "mydb", "user", "password")

if (conn_result.success) then:
conn = conn_result.conn
print("Connected to " + conn_result.driver + " database: " + conn_result.database)

// Execute a query (PostgreSQL uses $1, $2, etc.)
result = db_query(conn, "SELECT * FROM users WHERE age > $1", 18)

if (result.success) then:
print("Found " + str(result.count) + " users")
print("Columns: " + str(result.columns))
for (row in result.data):
print("User: " + row.name + ", Age: " + str(row.age))
end
end

// Execute an insert (returns rows_affected and last_insert_id)
insert_result = db_execute(conn, "INSERT INTO users (name, email) VALUES ($1, $2)", "John", "john@example.com")
if (insert_result.success) then:
print("Inserted " + str(insert_result.rows_affected) + " rows")
print("Last insert ID: " + str(insert_result.last_insert_id))
end

// Close connection
close_result = db_close(conn)
if (close_result.success) then:
print(close_result.message)
end
end

// Connect to MySQL (uses ? placeholders)
mysql_result = db_connect("mysql", "localhost", 3306, "mydb", "user", "password")
if (mysql_result.success) then:
mysql_conn = mysql_result.conn

// MySQL uses ? for placeholders
result = db_query(mysql_conn, "SELECT * FROM users WHERE age > ?", 18)
if (result.success) then:
print("Found " + str(result.count) + " MySQL users")
end

db_close(mysql_conn)
end

Batch Operations

// Prepare batch operations (PostgreSQL example)
operations = [
{"query": "INSERT INTO users (name, email) VALUES ($1, $2)", "args": ["Alice", "alice@example.com"]},
{"query": "INSERT INTO users (name, email) VALUES ($1, $2)", "args": ["Bob", "bob@example.com"]},
{"query": "UPDATE users SET active = $1 WHERE name = $2", "args": [true, "Alice"]}
]

// Execute batch
batch_result = db_execute_batch(conn, operations)

if (batch_result.success) then:
print("Batch executed successfully")
print("Total affected rows: " + str(batch_result.total_affected))

// Check individual results
for (i = 0; i < len(batch_result.results); i++):
result = batch_result.results[i]
if (result.success) then:
print("Operation " + str(i) + ": " + str(result.rows_affected) + " rows affected")
else:
print("Operation " + str(i) + " failed: " + result.error)
end
end
else:
print("Batch failed: " + batch_result.error)
end

// MySQL batch example
mysql_operations = [
{"query": "INSERT INTO users (name, email) VALUES (?, ?)", "args": ["Charlie", "charlie@example.com"]},
{"query": "INSERT INTO users (name, email) VALUES (?, ?)", "args": ["Diana", "diana@example.com"]}
]

mysql_batch_result = db_execute_batch(mysql_conn, mysql_operations)
if (mysql_batch_result.success) then:
print("MySQL batch completed: " + str(mysql_batch_result.total_affected) + " total rows")
end

Connection Pooling

// Create pool configuration
pool_config = {
"max_open": 10,
"max_idle": 5,
"max_lifetime": 3600
}

// Connect with connection pool
pool_conn = db_connect_with_pool("postgres", "localhost", 5432, "mydb", "user", "password", pool_config)

if (pool_conn.success) then:
conn = pool_conn.conn
print("Pool created with max_open: " + str(pool_conn.max_open))
print("Pool max_idle: " + str(pool_conn.max_idle))

// Configure pool settings (can be changed after creation)
config_result = db_configure_pool(conn, 20, 10, 7200) // max_open, max_idle, max_lifetime
if (config_result.success) then:
print("Pool configuration updated")
end

// Use the pooled connection
result = db_query(conn, "SELECT COUNT(*) as total FROM users")
if (result.success) then:
print("Total users: " + str(result.data[0].total))
end

close_result = db_close(conn)
if (close_result.success) then:
print(close_result.message)
end
end

Asynchronous Operations

// Execute query asynchronously
async_result = db_execute_async(conn, "SELECT * FROM large_table")

if (async_result.success) then:
operation_id = async_result.operation_id
print("Started async operation: " + operation_id)

// Check status periodically
while (true):
status = db_get_async_status(operation_id)

if (status.status == "completed") then:
print("Query completed with " + str(status.result.count) + " rows")
print("Affected rows: " + str(status.result.rows_affected))
print("Last insert ID: " + str(status.result.last_insert_id))
break
elif (status.status == "failed") then:
print("Query failed: " + status.error)
break
end

print("Operation still running...")
// Wait before checking again
sleep(1000)
end

// List all operations
operations = db_list_async_operations()
print("Total async operations: " + str(operations.count))

// Cleanup completed operations
cleanup_result = db_cleanup_async_operations()
if (cleanup_result.success) then:
print("Cleaned up " + str(cleanup_result.cleaned_count) + " operations")
end
else:
print("Failed to start async operation: " + async_result.error)
end

Real-time Streaming

// Define callback function
function on_data_change(event):
print("Stream ID: " + event.stream_id)
print("Table: " + event.table)
print("Operation: " + event.operation) // INSERT, UPDATE, DELETE
print("Timestamp: " + event.timestamp)

if (event.operation == "INSERT") then:
print("New data: " + str(event.new_data))
else if (event.operation == "UPDATE") then:
print("Old data: " + str(event.old_data))
print("New data: " + str(event.new_data))
else if (event.operation == "DELETE") then:
print("Deleted data: " + str(event.old_data))
end
end

// Define error callback
function on_stream_error(error):
print("Stream error: " + error.message)
print("Error code: " + str(error.code))
end

// Start streaming with callbacks
stream_result = stream_tables(conn, ["users", "orders"], on_data_change, on_stream_error)

if (stream_result.success) then:
stream_id = stream_result.stream_id
print("Streaming started with ID: " + stream_id)
print("Monitoring tables: " + str(stream_result.tables))

// Let it run for some time
sleep(30000) // 30 seconds

// Stop streaming
stop_result = db_stop_stream(stream_id)
if (stop_result.success) then:
print("Streaming stopped: " + stop_result.message)
end
else:
print("Failed to start streaming: " + stream_result.error)
end

System Functions

FunctionDescriptionExampleReturn Type
exit(code)Exit program with codeexit(0)void

Rule Engine - Fact Database Functions

FunctionDescriptionExampleReturn Type
fact_assert(type, id, data)Add fact to databasefact_assert("person", "john", {"age": 30})bool
fact_retract(type, id, data)Remove fact from databasefact_retract("person", "john", {})bool
fact_query(type, id, pattern)Query facts with patternfact_query("person", null, {"city": "Jakarta"})array
fact_exists(type, id, pattern)Check if fact existsfact_exists("person", "john", {})bool
fact_count(type, id, pattern)Count matching factsfact_count("person", null, {})int
fact_clear()Clear all factsfact_clear()void
fact_get_all()Get all factsfact_get_all()array

Complex Event Processing Functions

FunctionDescriptionExampleReturn Type
event_emit(type, data)Emit eventevent_emit("user_login", {"user": "john"})void
event_define_pattern(name, pattern)Define event patternevent_define_pattern("login_pattern", pattern)bool
event_get_window(name)Get event windowevent_get_window("recent_events")array
event_clear()Clear all eventsevent_clear()void
event_count(type)Count events by typeevent_count("user_login")int

For more detailed examples and advanced usage, see the Tutorial section.