Built-in Functions

A task-oriented reference for the functions available in the official Reference Distribution.

Start with the group that matches your task. Each entry gives its signature, what it is for, and a short example. echo writes output, but it is language syntax rather than a built-in function.

Availability by runtime

Most helpers are available in the Reference Distribution. If you are using another Polonio implementation, this table shows which capability provides each group. For a complete implementation inventory, see the built-in inventory.

LayerExamplesProfile availability
Language Coretype, to_string, to_number, countAll profiles
Standard Librarystrings, collections, math, dates, html_escapeReference Standard Library, Web Runtime, Data Runtime, Reference Distribution
Template Runtimeprint, printlnTemplate Runtime, Reference Distribution
Web Runtimerequest/response, sessions, CSRF, uploads, send_file, send_mailWeb Runtime, Reference Distribution
Data Runtimefile_*, dir_*, db_*Data Runtime, Reference Distribution

Use canonical names in new code: to_string, html_escape, http_status, and http_header. The older aliases remain supported for compatibility.

String Helpers (11)

Operate on any input coerced to a string.

FunctionDescription
len(value)Return the length (in characters) of the rendered value.
substr(text, start[, length])Slice text at the given start (negative values count from the end) and optional length.
lower(text)Convert ASCII characters to lowercase.
upper(text)Convert ASCII characters to uppercase.
trim(text)Strip whitespace on both ends.
replace(text, from, to)Replace every occurrence of one substring with another.
split(text, sep)Split into an array of segments using the separator.
contains(haystack, needle)Return true if the substring exists.
starts_with(text, prefix)Return true if text begins with prefix.
ends_with(text, suffix)Return true if text ends with suffix.
html_escape(value)Escape &, <, >, " and ' for HTML output. Compatibility alias: htmlspecialchars.

len(value)

Return the length (in characters) of the rendered value.

<% echo len(123.45) %>
Output: 6

substr(text, start[, length])

Slice text at the given start (negative values count from the end) and optional length.

<% echo substr("polonio", -3) %>
Output: nio

lower(text)

Convert ASCII characters to lowercase.

<% echo lower("Hola") %>
Output: hola

upper(text)

Convert ASCII characters to uppercase.

<% echo upper("hola") %>
Output: HOLA

trim(text)

Strip whitespace on both ends.

<% echo trim("  hi 
") %>
Output: hi

replace(text, from, to)

Replace every occurrence of one substring with another.

<% echo replace("a-b-a", "-", "/") %>
Output: a/b/a

split(text, sep)

Split into an array of segments using the separator.

<% var parts = split("a,b,c", ",") %>
<% echo parts[1] %>
Output: b

contains(haystack, needle)

Return true if the substring exists.

<% echo contains("preview", "view") %>
Output: true

starts_with(text, prefix)

Return true if text begins with prefix.

<% echo starts_with("docs/home", "docs/") %>
Output: true

ends_with(text, suffix)

Return true if text ends with suffix.

<% echo ends_with("index.html", ".html") %>
Output: true

html_escape(value)

Compatibility alias: htmlspecialchars(value). Both names have identical behavior.

Escape &, <, >, " and ' for HTML output.

<% echo html_escape("Rock & Roll") %>
Output: Rock & Roll

Array Helpers (9)

Manipulate ordered collections.

FunctionDescription
count(arrayOrObject)Return element (array) or key (object) count.
push(array, value)Append and return the new length.
pop(array)Remove and return the last element (or null).
shift(array)Remove and return the first element.
unshift(array, value)Insert at the beginning and return the new length.
concat(a, b)Return a new array containing both inputs.
join(array, sep)Join elements into a string using the separator.
slice(array, start[, length])Return a shallow slice from start with optional length.
range(count)Produce [0, 1, ..., count-1].

count(arrayOrObject)

Return element (array) or key (object) count.

<% echo count([1,2,3]) %>
Output: 3

push(array, value)

Append and return the new length.

<% var todos = ["a"]; echo push(todos, "b") %>
Output: 2

pop(array)

Remove and return the last element (or null).

<% var todos = ["x","y"]; echo pop(todos) %>
Output: y

shift(array)

Remove and return the first element.

<% var todos = ["x","y"]; echo shift(todos) %>
Output: x

unshift(array, value)

Insert at the beginning and return the new length.

<% var todos = ["x"]; echo unshift(todos, "y") %>
Output: 2

concat(a, b)

Return a new array containing both inputs.

<% var both = concat([1,2],[3]); echo count(both) %>
Output: 3

join(array, sep)

Join elements into a string using the separator.

<% echo join(["a","b"], ":") %>
Output: a:b

slice(array, start[, length])

Return a shallow slice from start with optional length.

<% echo count(slice([1,2,3,4], 1, 2)) %>
Output: 2

range(count)

Produce [0, 1, ..., count-1].

<% echo join(range(3), ",") %>
Output: 0,1,2

Object Helpers (5)

Work with string-keyed maps.

FunctionDescription
keys(object)Return sorted keys.
values(object)Return values sorted by key order.
has_key(object, name)Return true if a key exists.
get(object, name[, default])Fetch a value or default (null).
set(object, name, value)Assign and return the stored value.

keys(object)

Return sorted keys.

<% echo join(keys({"b":1,"a":2}), ",") %>
Output: a,b

values(object)

Return values sorted by key order.

<% echo join(values({"b":1,"a":2}), ",") %>
Output: 2,1

has_key(object, name)

Return true if a key exists.

<% echo has_key({"x":1}, "x") %>
Output: true

get(object, name[, default])

Fetch a value or default (null).

<% echo get({"x":1}, "x", 0) %>
Output: 1

set(object, name, value)

Assign and return the stored value.

<% var obj = {}; echo set(obj, "lang", "es") %>
Output: es

Math Helpers (10)

Numeric helpers (all arguments must be numbers).

FunctionDescription
abs(n)Absolute value.
floor(n)Round down.
ceil(n)Round up.
round(n)Round to nearest integer.
pow(base, exp)Raise base to exponent.
sqrt(n)Square root (throws on negative input).
min(a, b)Return the smaller number.
max(a, b)Return the larger number.
rand()Random floating-point value in [0, 1).
randint(min, max)Random integer in inclusive range.

abs(n)

Absolute value.

<% echo abs(-3) %>
Output: 3

floor(n)

Round down.

<% echo floor(3.8) %>
Output: 3

ceil(n)

Round up.

<% echo ceil(3.1) %>
Output: 4

round(n)

Round to nearest integer.

<% echo round(3.6) %>
Output: 4

pow(base, exp)

Raise base to exponent.

<% echo pow(2, 5) %>
Output: 32

sqrt(n)

Square root (throws on negative input).

<% echo sqrt(9) %>
Output: 3

min(a, b)

Return the smaller number.

<% echo min(4, 7) %>
Output: 4

max(a, b)

Return the larger number.

<% echo max(4, 7) %>
Output: 7

rand()

Random floating-point value in [0, 1).

<% echo rand() > 0 %>
Output: true

randint(min, max)

Random integer in inclusive range.

<% echo randint(1, 3) >= 1 %>
Output: true

Type Helpers (11)

Introspect and convert runtime values.

FunctionDescription
type(value)Return the runtime type name.
to_string(value)Serialize a value exactly as the output buffer would. Compatibility alias: tostring.
to_number(value)Convert strings/bools/null to numbers.
is_null(value)Return true if the value is null.
is_bool(value)Return true for booleans.
is_number(value)Return true for numeric values.
is_string(value)Return true for strings.
is_array(value)Return true for arrays.
is_object(value)Return true for objects.
is_function(value)Return true for user or builtin functions.

type(value)

Return the runtime type name.

<% echo type(123) %>
Output: number

to_string(value)

Compatibility alias: tostring(value). Both names have identical behavior.

Serialize a value exactly as the output buffer would.

<% echo to_string([1,2]) %>
Output: [1, 2]

to_number(value)

Convert strings/bools/null to numbers.

<% echo to_number(" 42 ") %>
Output: 42

is_null(value)

Return true if the value is null.

<% echo is_null(null) %>
Output: true

is_bool(value)

Return true for booleans.

<% echo is_bool(false) %>
Output: true

is_number(value)

Return true for numeric values.

<% echo is_number(3.14) %>
Output: true

is_string(value)

Return true for strings.

<% echo is_string("hi") %>
Output: true

is_array(value)

Return true for arrays.

<% echo is_array([1]) %>
Output: true

is_object(value)

Return true for objects.

<% echo is_object({}) %>
Output: true

is_function(value)

Return true for user or builtin functions.

<% echo is_function(type) %>
Output: true

Date Helpers (5)

Timestamps are seconds since UNIX epoch (UTC).

FunctionDescription
now()Return current UNIX timestamp.
date_format(epoch, pattern)Token-based formatter (YYYY, MM, DD, HH, mm, SS).
date_parts(epoch)Return an object with year/month/day/hour/minute/second.
date_add_days(epoch, days)Add days (can be fractional) via 86,400-second units.
date_parse(text)Parse YYYY-MM-DD or YYYY-MM-DD HH:MM:SS/T.

now()

Return current UNIX timestamp.

<% echo now() > 0 %>
Output: true

date_format(epoch, pattern)

Token-based formatter (YYYY, MM, DD, HH, mm, SS).

<% echo date_format(0, "YYYY-MM-DD") %>
Output: 1970-01-01

date_parts(epoch)

Return an object with year/month/day/hour/minute/second.

<% var p = date_parts(0); echo p["year"] %>
Output: 1970

date_add_days(epoch, days)

Add days (can be fractional) via 86,400-second units.

<% echo date_add_days(0, 1) %>
Output: 86400

date_parse(text)

Parse YYYY-MM-DD or YYYY-MM-DD HH:MM:SS/T.

<% echo date_parse("2026-01-05") %>
Output: 1767225600

Output Helpers (4)

Control how text is emitted from templates.

FunctionDescription
print(...values)Alias for echo.
println(...values)Print followed by newline.
nl2br(text)Convert newlines to <br>+ sequences.
debug(value)Describe a value on stderr (does not affect HTML).

print(...values)

Alias for echo.

<% print("hi") %>
Output: hi

println(...values)

Print followed by newline.

<% println("hi") %>
Output: hi

nl2br(text)

Convert newlines to <br>+ sequences.

<% echo nl2br("a
b") %>
Output: a
b

debug(value)

Describe a value on stderr (does not affect HTML).

<% debug(_SERVER) %>
Output: stderr

Response Helpers and URL Utilities (6)

Layer: http_status, http_header, http_content_type, and redirect belong to the Web Runtime and need a ResponseContext; CGI and the development server are the reference distribution's current adapters. urlencode and urldecode belong to the Standard Library and do not require HTTP.

FunctionDescription
http_status(code)Set the outgoing HTTP status line (100–599). Compatibility alias: status.
http_header(name, value)Add or overwrite headers. Compatibility alias: header.
http_content_type(value)Set the Content-Type header.
redirect(target[, status])Set Location header plus 3xx status (default 302).
urlencode(text)Percent-encode query-string fragments.
urldecode(text)Decode percent-encoded strings.

http_status(code)

Compatibility alias: status(code). Both names have identical behavior.

Set the outgoing HTTP status line (100–599).

<% http_status(302) %>
Output: Status: 302

http_header(name, value)

Compatibility alias: header(name, value). Both names have identical behavior.

Add or overwrite headers.

<% http_header("X-Test", "ok") %>
Output: X-Test: ok

http_content_type(value)

Set the Content-Type header.

<% http_content_type("text/plain") %>
Output: Content-Type: text/plain

redirect(target[, status])

Set Location header plus 3xx status (default 302).

<% redirect("/login") %>
Output: Status: 302 / Location: /login

urlencode(text)

Percent-encode query-string fragments.

<% echo urlencode("hola mundo") %>
Output: hola+mundo

urldecode(text)

Decode percent-encoded strings.

<% echo urldecode("hola+mundo") %>
Output: hola mundo

Storage Functions (10)

Layer: Data Runtime. The official reference distribution provides a sandboxed storage API for reading and writing files. All filesystem access occurs inside the directory referenced by the POLONIO_STORAGE_PATH environment variable, keeping templates away from arbitrary host files.

Rules enforced by every storage builtin:

FunctionDescription
file_read(path)Read a file as a string.
file_write(path, content)Write (replace) the contents of a file.
file_append(path, content)Append text to a file, creating it if missing.
file_exists(path)Return true if a regular file exists.
file_delete(path)Delete a regular file if it exists.
file_size(path)Return file size in bytes.
file_modified(path)Return last modification time in epoch seconds.
dir_create(path)Create a directory tree relative to the storage root.
dir_exists(path)Return true if a directory exists.
dir_list(path)List directory entries (names only) sorted ascending.

file_read(path)

Read the contents of a file inside the storage root and return it as a string.

Arguments:

  • path — relative path to a regular file

Returns: string containing the file contents.

Errors:

  • storage root not configured
  • absolute or escaping path
  • file missing
  • path refers to a directory

Example:

<%
var text = file_read("notes/welcome.txt")
echo text
%>

file_write(path, content)

Write the provided content to a file. The file is created or replaced atomically; parent directories must already exist.

Arguments:

  • path — relative file path (parent directory must exist)
  • content — value converted to a string before writing

Returns: null.

Errors:

  • storage root not configured
  • absolute or escaping path
  • missing parent directory
  • target is a directory

Example:

<%
dir_create("drafts")
file_write("drafts/post.txt", "Hello from Polonio!")
%>

file_append(path, content)

Append content to a file, creating the file when it does not exist. Parent directories must exist and the target cannot be a directory.

Arguments:

  • path — relative file path
  • content — value converted to a string before appending

Returns: null.

Errors:

  • storage root not configured
  • absolute or escaping path
  • missing parent directory
  • target is a directory

Example:

<%
dir_create("logs")
file_append("logs/app.log", "started\n")
%>

file_exists(path)

Test whether a regular file exists at the given relative path.

Arguments:

  • path — relative file path

Returns: true if a regular file exists, otherwise false.

Errors:

  • storage root not configured
  • absolute or escaping path

Example:

<% echo file_exists("drafts/post.txt") %>

file_delete(path)

Delete a regular file if it exists under the storage root.

Arguments:

  • path — relative file path

Returns: true if a file was deleted, false if nothing existed.

Errors:

  • storage root not configured
  • absolute or escaping path
  • path refers to a directory

Example:

<%
if file_delete("drafts/post.txt")
  echo "Removed draft"
end
%>

file_size(path)

Return the size of a regular file in bytes.

Arguments:

  • path — relative file path

Returns: number representing the byte length.

Errors:

  • storage root not configured
  • absolute or escaping path
  • file missing
  • path refers to a directory

Example:

<%
var size = file_size("drafts/post.txt")
echo "Size: " .. size .. " bytes"
%>

file_modified(path)

Return the last modification timestamp of a file as Unix epoch seconds.

Arguments:

  • path — relative file path

Returns: number representing seconds since the Unix epoch.

Errors:

  • storage root not configured
  • absolute or escaping path
  • file missing
  • path refers to a directory

Example:

<%
var updated_at = file_modified("drafts/post.txt")
echo "Last updated: " .. updated_at
%>

dir_create(path)

Create the requested directory (and any intermediate directories) under the storage root.

Arguments:

  • path — relative directory path

Returns: true whether the directory already existed or was just created.

Errors:

  • storage root not configured
  • absolute or escaping path
  • path already exists as a file

Example:

<% dir_create("uploads/images") %>

dir_exists(path)

Check whether a directory exists.

Arguments:

  • path — relative directory path

Returns: true if the path exists and is a directory; otherwise false.

Errors:

  • storage root not configured
  • absolute or escaping path

Example:

<%
if dir_exists("uploads")
  echo "Uploads ready"
end
%>

dir_list(path)

Return an array of entry names (files and directories) sorted ascending for the requested directory.

Arguments:

  • path — relative directory path

Returns: array of strings (entry names).

Errors:

  • storage root not configured
  • absolute or escaping path
  • path missing or not a directory

Example:

<%
var entries = dir_list("posts")
for name in entries
  echo "<li>" .. name .. "</li>"
end
%>

Database (SQLite)

Layer: Data Runtime. The official reference distribution includes a SQLite interface for persistent storage. All database files live inside the directory indicated by POLONIO_STORAGE_PATH; paths are resolved relative to that root and may not escape it.

FunctionDescription
db_connect(path)Open or create a SQLite database file.
db_close()Close the current database connection.
db_query(sql[, params])Execute a SELECT statement and return rows.
db_exec(sql[, params])Execute INSERT/UPDATE/DELETE and return affected rows.
db_last_insert_id()Return the last inserted row id.
db_begin()Start a transaction.
db_commit()Commit the current transaction.
db_rollback()Roll back the current transaction.

db_connect(path)

Open (or create) a SQLite database inside the storage sandbox.

Arguments:

  • path — relative path to the database file (parent directory must exist)

Returns: null.

Errors:

  • storage root not configured
  • absolute or escaping path
  • parent directory missing
  • SQLite open failure

Example:

<%
dir_create("data")
db_connect("data/app.db")
%>

db_close()

Close the active database connection.

Arguments: none.

Returns: null.

Errors:

  • database not connected

Example:

<% db_close() %>

db_query(sql[, params])

Execute a SELECT statement and return an array of objects (one per row). Column values map to strings, numbers, or null depending on SQLite types:

[
  {"id": 1, "name": "Ada"},
  {"id": 2, "name": "Grace"}
]

Arguments:

  • sql — SQL string
  • params (optional) — array of positional parameters bound to ?

Returns: array of row objects.

Errors:

  • database not connected
  • unsupported parameter type
  • SQLite prepare/step error

Example:

<%
var users = db_query("select id, name from users where active = ?", [true])
for user in users
  echo user["name"]
end
%>

db_exec(sql[, params])

Execute INSERT/UPDATE/DELETE/DDL statements and return the number of rows affected (per sqlite3_changes()).

Arguments:

  • sql — SQL string
  • params (optional) — array of positional parameters

Returns: number of rows changed.

Errors: same as db_query.

Example:

<% db_exec("insert into users(name) values(?)", ["Ada"]) %>

db_last_insert_id()

Return the row id generated by the most recent insert on the connection.

Arguments: none.

Returns: number (row id).

Errors: database not connected.

Example:

<%
db_exec("insert into users(name) values(?)", ["Ada"])
var id = db_last_insert_id()
%>

db_begin()

Start a transaction. Only one transaction can be active at a time.

Arguments: none.

Returns: null.

Errors:

  • database not connected
  • transaction already active

Example:

<%
db_begin()
db_exec("insert into logs(message) values(?)", ["start"])
db_commit()
%>

db_commit()

Commit the active transaction.

Arguments: none.

Returns: null.

Errors:

  • database not connected
  • no active transaction
  • SQLite commit failure

Example:

<%
db_begin()
db_exec("update counters set value = value + 1")
db_commit()
%>

db_rollback()

Roll back the active transaction.

Arguments: none.

Returns: null.

Errors:

  • database not connected
  • no active transaction
  • SQLite rollback failure

Example:

<%
db_begin()
db_exec("delete from users where id = ?", [user_id])
db_rollback()
%>

Request, Session, Security, and Delivery APIs

Layer: Web Runtime. These APIs require a Web Runtime request context; CGI and the development server are the reference distribution's current adapters. Calls made without the required context raise a runtime error. Argument mismatches also raise runtime errors.

Request

request_body()
Returns the raw request body string. Example: var raw = request_body().
request_header(name)
Accepts a string header name and returns its string value or null. Example: request_header("Content-Type").
request_headers()
Returns an object of request headers. Example: keys(request_headers()).
request_json()
Parses the raw body and returns the JSON value; invalid JSON raises an error. Example: var data = request_json().
cookies()
Returns the parsed cookie object. Example: cookies()["theme"].

Sessions

Require POLONIO_SESSION_SECRET; otherwise they raise an error. Data is stored in a signed cookie and persists only when the response can emit the updated cookie.

session_get(key[, default])
String key; returns the stored value, default, or null. Example: session_get("user_id").
session_set(key, value)
String key and any value; stores it and returns null. Example: session_set("flash", "Saved").
session_unset(key)
String key; removes it and returns null. Example: session_unset("flash").
session_clear()
Removes all session values and returns null. Example: session_clear().

Security

random_token(bytes)
Number of random bytes (1 through 1024); returns a URL-safe token. Invalid sizes raise an error. Example: random_token(32).
csrf_token()
Requires a session; returns the current session-backed token. Example: <input value="<% echo csrf_token() %>">.
csrf_verify(token)
Requires a session and a string token; returns bool. Example: if csrf_verify(_POST["csrf"]).
hash_password(password)
Accepts a string and returns a password hash. Example: var hash = hash_password("secret").
verify_password(password, hash)
Accepts strings and returns bool. Example: verify_password(input, hash).

Uploads, file responses, and mail

upload_save(file, path)
Accepts a `_FILES` file object and a relative storage path; moves the temporary upload and returns the saved path. Requires POLONIO_STORAGE_PATH. Example: upload_save(_FILES["photo"], "uploads/photo.bin").
send_file(path[, opts])
Accepts a relative sandboxed path and optional object with string content_type and/or download_name, finalizes the CGI/server response, and returns null. Missing/unsafe files raise errors. Example: send_file("reports/latest.txt").
send_mail(to, subject, body[, headers])
Accepts strings and optional header object; writes an .eml file to storage outbox and returns its path. Reserved/injected headers raise errors. It does not send SMTP mail. Example: send_mail("[email protected]", "Hi", "Body").

Compatibility aliases

http_status(code) has the compatibility alias status(code); http_header(name, value) has header(name, value). Both aliases have identical behavior, including response effects. http_content_type(value) sets a string content type. redirect(target[, status]) accepts a string target and optional 3xx-compatible number, sets Location/status, and returns null.

html_escape(value) has compatibility alias htmlspecialchars(value); to_string(value) has compatibility alias tostring(value). Both pairs have identical successful behavior.