Skip to content
Revar Desmera edited this page Nov 25, 2026 · 16 revisions

Built-in Functions

Functions return values. They can appear anywhere an expression can.

Argument names are ignored by most built-in functions. As in OpenSCAD, sin(a=90), pow(y=3, x=2) and max(a=1, b=5) read their arguments in the order written, whatever they are called: 1, 9 and 5. Only textmetrics(), fontmetrics(), import(), dxf_dim() and dxf_cross() also match arguments by name.


Mathematical

Function Result
abs(x) Absolute value
sign(x) -1, 0 or 1
ceil(x) Smallest integer ≥ x
floor(x) Largest integer ≤ x
round(x) Nearest integer; halves round away from zero
sqrt(x) Square root; nan for negative x
ln(x) Natural logarithm
log(x) / log(b, x) Base-10 logarithm, or the base-b logarithm: log(2, 8) is 3
exp(x) ex
pow(b, e) be — same as the ^ operator
min(a, b, …) / min(list) Smallest value
max(a, b, …) / max(list) Largest value
norm(v) Euclidean length of a vector
cross(a, b) Cross product of two 3-vectors (or the scalar 2D cross of two 2-vectors)
linear_solve(A, b) BelfrySCAD extension. Solves A·x = b, and reports the determinant and whether A is singular
echo(round(2.5));          // 3
echo(round(-2.5));         // -3
echo(round(0.49999999999999994));   // 0 -- rounding is exact
echo(pow(2, 10));          // 1024
echo(2 ^ 10);              // 1024
echo(norm([3, 4]));        // 5
echo(cross([1,0,0], [0,1,0]));   // [0, 0, 1]
echo(max([4, 9, 2]));      // 9

Trigonometry

Every angle here is in DEGREES

Not radians — in both directions. sin, cos and tan take degrees, and asin, acos, atan and atan2 return degrees.

This matches OpenSCAD, and differs from C, Python, JavaScript and almost every other language's maths library. A formula copied from anywhere else will be silently wrong rather than an error.

Function Takes Returns
sin(a) cos(a) tan(a) an angle in degrees a ratio
asin(x) acos(x) a ratio, −1…1 (nan outside) an angle in degrees
atan(x) a ratio an angle in degrees, −90…90
atan2(y, x) two lengths an angle in degrees, −180…180
echo(sin(30));             // 0.5      -- 30 DEGREES, not 30 radians
echo(cos(60));             // 0.5
echo(tan(45));             // 1
echo(asin(0.5));           // 30       -- degrees back out
echo(acos(0.5));           // 60
echo(atan(1));             // 45
echo(atan2(1, 1));         // 45
echo(atan2(-1, -1));       // -135     -- both signs respected

for (a = [0:15:345]) rotate([0,0,a]) translate([20,0,0]) cylinder(h=5, r=2);

The mistake this causes. PI exists, so a radians habit compiles and runs:

echo(sin(PI/2));           // 0.0274121   <- NOT 1

PI/2 is about 1.57, and the sine of 1.57 degrees is 0.0274. Nothing warns, because 1.57 is a perfectly good angle. Convert explicitly if you are working from a radians formula:

function deg(r) = r * 180 / PI;    // radians -> degrees
function rad(d) = d * PI / 180;    // degrees -> radians

echo(sin(deg(PI/2)));      // 1

Exact at the quarter turns. cos(90) is exactly 0, not a 6.1e-17 residue, and likewise sin(180) and sin(360). So a value used as a coordinate lands on the axis rather than a hair off it, and == 0 behaves.

rands

rands(min_value, max_value, value_count, seed_value = undef)

Returns a list of value_count pseudo-random numbers in [min_value, max_value). Passing the same seed_value gives the same sequence, which is what you want for a reproducible model.

pts = rands(0, 100, 20, 42);
for (i = [0:2:18]) translate([pts[i], pts[i+1], 0]) cylinder(h=5, r=1);

Without a seed_value, results differ on every render — the model is no longer deterministic, and the render cache cannot reuse anything that depends on it.

lookup

lookup(key, table)

Linearly interpolates key into a table of [key, value] pairs. Keys outside the table clamp to the nearest end. A key that is not a finite number -- inf, nan, a string -- gives undef and a warning, as in OpenSCAD.

profile = [[0, 5], [10, 8], [20, 2]];
echo(lookup( 5, profile));    // 6.5
echo(lookup(99, profile));    // 2

linear_solve

A BelfrySCAD extension — not in OpenSCAD. One pivoted LU factorization answers three questions at once, so asking for all three costs no more than asking for one.

Note: BOSL2 also defines linear_solve(), and a user function shadows a builtin — so with include <BOSL2/std.scad> you get BOSL2's, which returns a bare vector rather than an object with .x. See Language Extensions.

A = [[1, 2, 3],
     [2, 1, 1],
     [3, 1, 2]];

r = linear_solve(A, [14, 7, 11]);

echo(r.x);           // [1, 2, 3]   -- the solution
echo(r.det);         // -4          -- the determinant
echo(r.singular);    // false

Each row of A is one equation's coefficients; each entry of b is that equation's right-hand side. The row above reads 1x + 2y + 3z = 14.

Leave b out for the determinant alone. Both this and the solve are far quicker than doing the arithmetic in OpenSCAD itself — a 64x64 solve is about 1000x faster than BOSL2's linear_solve(), and BOSL2's determinant() expands by cofactors, taking 31 seconds at n=11 where this takes no measurable time (figures):

echo(linear_solve(A).det);        // -4

Solve against the identity and the answer is the inverse:

inv = linear_solve(A, [[1,0,0],[0,1,0],[0,0,1]]).x;
echo(inv[0]);                     // [-0.25, 0.25, 0.25]

A matrix with no unique solution is reported rather than treated as an error, so check singular before using x (which is undef in that case):

echo(linear_solve([[1,2],[2,4]], [1,2]).singular);   // true

Square systems only, and a non-square or non-numeric matrix warns and returns undef. Full details, including a four-unknown worked example and the tolerance used to decide singularity: Language Extensions.


Strings and lists

Function Result
str(a, b, …) Concatenates every argument into one string
len(x) Length of a string or list; undef for a number
concat(a, b, …) Concatenates lists, splicing one level; non-lists are appended as single elements
chr(n) / chr(list) Unicode code point(s) → string
ord(s) First character of a string → code point
search(match, table, num_returns = 1, index = 0) Index search
echo(str("width is ", 10, "mm"));      // "width is 10mm"
echo(len("hello"));                    // 5
echo(len([1,2,3]));                    // 3
echo(concat([1,2], [3,4], 5));         // [1, 2, 3, 4, 5]
echo(chr(65));                         // "A"
echo(chr([72, 105]));                  // "Hi"
echo(ord("A"));                        // 65

chr() skips non-finite or undef elements inside a list argument rather than failing the whole call, and returns "" for a non-finite scalar.

search

echo(search("b", "abcabc"));                    // [1]
echo(search("b", "abcabc", 0));                 // [[1, 4]]   — 0 = all matches
echo(search(3, [[1,"a"],[2,"b"],[3,"c"]]));     // [2]

num_returns = 0 returns every match instead of just the first. index selects which element of each table row is compared.


Type checks

Function True when
is_undef(x) x is undef
is_bool(x) x is true or false
is_num(x) x is a number
is_string(x) x is a string
is_list(x) x is a list or vector
is_function(x) x is a function literal value
is_object(x) x is an object
module part(size) {
    assert(is_num(size) || is_list(size), "size must be a number or a vector");
    // ...
}

Two things to know:

  • is_num(nan) is false, even though nan is numerically a float. inf and -inf both pass. This matches OpenSCAD.
  • is_function(f) is false for a named function f declared with function f(x) = …. Only values created by a function literal (g = function (x) …) satisfy it.

Not built in

is_range, is_nan and is_finite are not builtins, despite the naming. They are ordinary functions defined by BOSL2's utility.scad. Without BOSL2 included, calling them warns Ignoring unknown function '...' and evaluates to undef — exactly as in OpenSCAD.


Objects

Feature name object-function — supported_feature("object-function") is 1 here. Objects are always available in BelfrySCAD; upstream OpenSCAD has them only behind --enable=object-function, so a script that needs them should check rather than assume.

An object is a keyed container, comparable to a dictionary.

Function Result
object(k = v, …) Creates an object
object(obj, …) Merges an existing object's keys in
object(…, [[k, v], [k]]) Sets k to v; a single-element entry deletes k
is_object(x) Type check
has_key(obj, key) true if the string key exists; undef if obj is not an object
cfg = object(width = 20, height = 10, name = "plate");

echo(cfg.width);              // 20
echo(cfg["height"]);          // 10
echo(has_key(cfg, "name"));   // true

for (k = cfg) echo(k, cfg[k]);   // iterating an object yields its keys

echo() and str() print an object as { width : 20, height : 10, name : "plate" }, the format OpenSCAD 2026.11 adopted; an empty one is { }, and a key that is not a plain identifier is quoted ({ "my key" : 1 }). Two objects are equal when they hold the same keys with equal values, in any order, so object(a = 1, b = 2) == object(b = 2, a = 1) is true, as in OpenSCAD 2026.11. (BelfrySCAD 1.101 and earlier printed { width = 20; height = 10; … } and compared keys in order.)

Deriving one object from another

An unnamed argument is either another object — whose keys are merged in — or a list of entries. Each entry is [key, value] to set, or the single-element [key] to delete:

base = object(a = 42, b = 53, c = 8);

derived = object(base, [["d", 18], ["b"]]);
echo(derived);        // { a : 42, c : 8, d : 18 }

Deleting removes the key outright rather than blanking it. Since an object keeps its keys in insertion order, that is observable — a key deleted and then set again lands at the end:

echo(object(base, [["b"], ["b", 99]]));   // { a : 42, c : 8, b : 99 }
echo(object(base, [["b", 99], ["b"]]));   // { a : 42, c : 8 }

Deleting a key that isn't there is a silent no-op. A malformed entry — empty, longer than two elements, or with a non-string key — warns and makes the whole call undef.

Setting an existing key overwrites it in place, keeping its position:

echo(object(a = 42, b = 1, a = 99));      // { a : 99, b : 1 }

Objects from elsewhere

Objects are also what import() produces from a .json file, so external configuration drops straight into a model:

cfg = import("dimensions.json");
cube([cfg.x, cfg.y, cfg.z]);

render() in expression position also returns an object — the measurements and mesh of geometry you have just built.

Both can be inspected in the Object viewer.

Objects are an experimental feature in OpenSCAD (--enable=object-function). They are always available in BelfrySCAD.


Font functions

textmetrics

textmetrics(text, size = 10, font = "", direction = "", language = "", script = "",
            halign = "left", valign = "baseline", spacing = 1, em)

Measures a string laid out with the same arguments as text(). Returns an object:

Every argument can be given positionally, in the order above — note that this is not the order text() uses, and text() accepts only its first three positionally. Passing them by name sidesteps the difference entirely, and is what the examples here do. em sets the size as the font's em square instead of size; see size or em.

Key Meaning
position [x, y] of the lower-left corner of the inked area
size [width, height] of the inked area
ascent Highest inked point above the baseline
descent Lowest inked point below the baseline (negative)
offset [x, y] shift applied by halign / valign
advance [x, 0] — total pen advance, including side bearings
m = textmetrics("BelfrySCAD", size=12);
// A plate sized to fit the text, with a 3 mm margin
linear_extrude(2) translate(m.position - [3,3]) square(m.size + [6,6]);
linear_extrude(3) text("BelfrySCAD", size=12);

The inked box is measured as OpenSCAD measures it: each glyph's box is grown outward to a grid of size × 0.00064, so position, size, ascent and descent match OpenSCAD's to the digit rather than hugging the outline exactly.

Note size (ink extent) differs from advance (layout width) — use advance to position the next string, and size to draw a box around this one.

fontmetrics

fontmetrics(size = 10, font = "", em)

Returns an object describing the font itself. Every argument is positional, so fontmetrics(10, "Liberation Sans:style=Bold") works as well as the named form. em replaces size, as it does for text():

Key Meaning
nominal { ascent, descent } from the font's declared metrics
max { ascent, descent } from the font's actual glyph bounding box
interline Recommended baseline-to-baseline distance
font { family, style } of the font actually resolved — check this when a font= did not do what you expected; see Fonts
fm = fontmetrics(size=10);
for (i = [0:2])
    translate([0, -i * fm.interline, 0])
        linear_extrude(1) text(lines[i], size=10);

Reading a DXF drawing

Drive a model from a CAD drawing's own dimensions, rather than retyping them.

Function Result
dxf_dim(file, layer, name, origin, scale) The value of a DIMENSION entity in the file
dxf_cross(file, layer, origin, scale) [x, y] where two LINE entities cross
width  = dxf_dim(file="bracket.dxf", layer="dims", name="width");
center = dxf_cross(file="bracket.dxf", layer="datum");

translate(center) cube([width, 10, 3]);

layer and name narrow the search — omit either to take the first match anywhere. origin shifts every coordinate and scale multiplies it, so the numbers come back in your model's units.

Supported dimension types: linear (rotated / horizontal / vertical), aligned, angular, diameter, radius and ordinate. An angular-3-point dimension is not supported, and warns — as it does in OpenSCAD.

Both return undef, with a warning, when the file is missing or nothing matches:

WARNING: Can't open DXF file 'bracket.dxf'!
WARNING: Can't find dimension 'width' in 'bracket.dxf', layer 'dims'!
WARNING: Can't find cross in 'bracket.dxf', layer 'datum'!

dxf_cross needs two LINE entities that genuinely cross; parallel lines have no intersection and warn the same way.


Other

Function Result
version() Version as [year, month, day] — [2026, 1, 1], the OpenSCAD release BelfrySCAD tracks
version_num() That same version as year*10000 + month*100 + day, so 20260101
version_num(v) Any [y, m] or [y, m, d] folded the same way, so version_num([2019, 5, 0]) is 20190500
parent_module(n) Name of the module n levels up the call stack
fragments(r) / fragments(d = …) How many sides a circle of that radius gets from the current $fn/$fe/$fa/$fs — the same rule circle() uses. r defaults to 1, and the $ variables can be passed in the call: fragments(10, $fn = 6) is 6. New in OpenSCAD 2026.11
supported_feature(name) BelfrySCAD extension. The level at which this build implements a named feature, or 0 — see Language Extensions
PI 3.14159… (a constant, not a function)
echo(version());                      // [2026, 1, 1]
echo(version_num());                  // 2.02601e+7 — the value is 20260101
echo(version_num([2019, 5, 0]));      // 2.01905e+7 — fold any release to compare

// echo() prints six significant digits, so compare the numbers rather than
// reading them off the console:
if (version_num() >= version_num([2026, 1, 1])) echo("new enough");
echo(PI);
module a() { b(); }
module b() { echo(parent_module(1)); }    // "a"

echo(fragments(10));                         // 30, from the defaults $fa = 12, $fs = 2
echo(fragments(r = 10, $fa = 1, $fs = 0.4)); // 158

See also $parent_modules in Special Variables.


Behavior with wrong types

Passing something non-numeric to a numeric function never fails the render. What it produces depends on the function.

Booleans are rejected — they yield undef, matching OpenSCAD. Without this, true would silently behave as 1 in every numeric context.

echo(abs(true));        // undef
echo(max(true, 1));     // undef

Every numeric function yields undef for undef, string or list input, matching OpenSCAD. So do the arithmetic operators (1 + undef is undef).

echo(abs(undef));       // undef
echo(sqrt("hi"));       // undef
echo(cos(undef));       // undef
echo(acos([1,2]));      // undef

Too few arguments is a type error too, rather than a call against an implicit zero:

echo(abs());            // undef
echo(pow(2));           // undef

This is what makes a misspelled variable show up as an obvious undef rather than quietly becoming 0 and producing plausible-looking geometry.

Extra trailing arguments are ignored, where OpenSCAD rejects the call — the one remaining difference in this area, and a harmless one.

Behavior with nan and inf

Non-finite numeric input follows OpenSCAD exactly:

Expression Result
sqrt(-1), ln(-1), asin(2) nan
ceil(inf), floor(nan) passes the value through
pow(0, -1) inf
pow(-8, 0.5) nan
sin(inf) nan
max(0/0, 1) nan
max(1, 0/0) 1

The last two are position-dependent because nan never compares greater or less than anything — a quirk inherited from OpenSCAD, not a design choice. Don't rely on it.

cross() returns undef if any component of either input is nan or inf, rather than producing a partly-nan vector.

Clone this wiki locally