Skip to content

Directives

Updated

A directive is a line that starts with #. Directives are applied to the script’s source before the script runs, in a step called preprocessing. They let you name constants, write small macros, keep or drop code depending on the device, and declare things about the script that the runtime reads: its hooks, its editor fields, what it shares. This page covers the bare directives that decide which lines are compiled, the predefined constants, macros and device flags, and the list of #pragma directives with the page that documents each one.

There are two kinds of directive, by one rule:

  • A bare directive acts on preprocessing itself. It decides which lines are compiled and which output they go to, or it reports while preprocessing: #define, #if, #error, #editor_begin.
  • A #pragma declares something about the script that the runtime reads: its hooks, its editor fields, what it shares. #pragma lifecycle, #pragma slot, #pragma export.

Every source line keeps its line number through preprocessing, so an error always points at the line you wrote. A directive may have spaces after the # (# define) and leading spaces before it. A # at the start of a line inside a template literal or a block comment is text, not a directive, and a class’s private member (#count = 0;) is code.

Directive What it does
#define NAME value A constant, substituted in the code.
#define NAME(a, b) body A function-like macro. In the body, #a is the text of argument a as a string: #define SHOW(x) log(#x, x) makes SHOW(speed) log speed 4.
#define NAME body \ A value or body continued on the next line, after a trailing \.
#undef NAME Remove a definition.
#if expr Compile the lines up to the next #elif, #else or #endif if expr is true.
#ifdef NAME / #ifndef NAME Compile the lines if NAME is, or is not, defined.
#elif expr Another branch of an #if.
#else The branch taken when no other was.
#endif End an #if, #ifdef or #ifndef block.
#error message Stop the script with this message.
#warning message Report this message as a warning in the browser console and carry on.
#editor_begin / #editor_end The lines between are editor code, absent from play. See Editor scripts.
#editor_only The whole script is editor code and never runs in play. See Editor scripts.

A constant gives a value a name; a macro is a small piece of code with parameters that the preprocessor pastes in where it is used. Both are replaced in the text before the script runs, so they cost nothing at run time.

Macros.jx
#define SPEED 4
#define GREETING "Hello"
#define CLAMP(v, lo, hi) Math.min(Math.max(v, lo), hi)
#pragma lifecycle(update)
function update(dt) {
self.parent.position.x = CLAMP(self.parent.position.x + SPEED * dt, -10, 10);
}
log(GREETING);
  • A constant’s value is the rest of the line, with any trailing // comment removed. A // inside a quoted string, as in a URL, stays part of the value.
  • A name is substituted only as a whole word, never inside a string or comment, and never as a property name: Number.EPSILON stays as written even though EPSILON is defined.
  • A macro’s arguments are substituted wherever its parameters appear in the body, inside strings too.
  • Definitions are not substituted inside a #pragma: write max=8, not max=MAX_SIZE.
  • Defining a name twice is an error. #undef it first.
  • An #editor_begin region does not see definitions: write plain JavaScript there.

Conditions keep or drop whole blocks of code. A dropped block is not compiled at all, so it may even use names that do not exist on the device.

Quality.jx
#if IS_MOBILE || IS_HEADSET
const quality = 'low';
#elif defined(IS_TOUCH)
const quality = 'medium';
#else
const quality = 'high';
#endif
#ifndef IS_XR_CAPABLE
#warning this script is meant for XR
#endif
  • An #if expression compares literals: numbers, strings, true, false, null, with the usual operators (==, !=, <, >, <=, >=, &&, ||, !, +, -, *, /, %, ? : and parentheses). Defined names are substituted first, and defined(NAME) is true when NAME is defined.
  • A name that is not defined reads as 0. So #if IS_HEADSET and #ifdef IS_HEADSET both work on every device.
  • Blocks nest. Every #if needs its #endif, and nothing may follow an #else but #endif.
  • A #pragma can sit inside an #if block, but an #if cannot sit inside a multi-line #pragma: put the condition around the whole pragma.
Name Value
M_PI π, half a turn in radians
M_TAU 2π, a full turn in radians
M_HALF_PI π/2, a quarter turn in radians
EPSILON 1e-6, a tolerance for positions and angles (Number.EPSILON is far too small for them)
MAX_INT, MIN_INT The largest and smallest safe integers
SCRIPTING_RUNTIME_VERSION The scripting runtime’s version number
__LINE__ The current source line number
__FILE__ The name of the Behavior entity running the script, as a string
__DATE__, __TIME__ The date and time the script was preprocessed, as strings in the device’s locale
Macro What it does
DEG_TO_RAD(x) Degrees to radians.
RAD_TO_DEG(x) Radians to degrees.
ASSERT(x) Throws Assertion failed: x, with the text of x, when x == false.

ASSERT compares with == false, so it throws for false, 0, '' and '0', but not for null or undefined. Test those explicitly: ASSERT(target != null).

Each device preprocesses its scripts when it loads them, with flags describing that device. A flag is defined, as true, only where it holds; elsewhere it is undefined.

Flag Defined when
IS_MOBILE The device is a phone or tablet.
IS_TOUCH The device has a touch screen.
IS_HEADSET The page runs in a headset’s own browser.
IS_XR_CAPABLE The browser has the WebXR API. Desktop browsers can have it too: use await Device.supportsImmersiveVR() for an exact answer.
PLATFORM_WINDOWS, PLATFORM_MACOS, PLATFORM_LINUX, PLATFORM_ANDROID, PLATFORM_IOS The operating system. One of them, at most.

The same facts are available while the script runs, through the Device global: Device.isMobile(), Device.isTouch(), Device.isHeadset(), Device.hasWebXR(). Choose between them like this:

  • A flag drops the other branch’s code entirely, so it costs nothing at run time. Use it for code that only makes sense on some devices.
  • Device lets one build of the code decide later, for example after an await.
Directive What it does Page
#pragma lifecycle(startup, update, …) Declare the hooks the engine calls; hook=function uses another name. Lifecycle hooks
#pragma slot(ref=…, type=…, …) Declare an editor field and the variable that holds its value. Slots
#pragma enum(ref=Name, [A, B=10, C]) Named integers, usable as Dropdown items. Slots
#pragma type(ref=Name, fields={ … }) A record type for slots. Slots
#pragma export(name) Publish a variable to other scripts. Modules
#pragma import(name) Read another script’s export. Modules
#pragma import(Name="https://…/lib.js") Load a module from a URL. Dynamic imports
#pragma dont_unload() Keep this entity when its scene is switched away. Scene switching
#pragma tool(name=…, description=…, …) Declare a tool an AI agent can call. Only in an AI tool script. AI agents

Shader sources for a Shader Material use their own pragmas in the same grammar; see Graphics.

A pragma may span several lines, up to the ) that closes it, and may end with a trailing comma. // and /* */ comments may end its lines:

MultiLine.jx
#pragma slot(
ref = speed, // the variable
type = Slider,
min = 0,
max = 10,
label = "Speed (m/s)",
group = "Movement",
)

Values follow two rules:

  • Quoted, anything goes. A quoted value is taken literally and stays text: default="5" is the string "5". It keeps any ,, =, ( or ) inside it, in lists too: default=["a, b", "c)"]. Write a quote inside one as \" or \'. Every other backslash stays as written, so a pattern like "^\d+$" keeps its meaning.
  • Unquoted, kept as written up to the next , or ). Numbers become numbers (4, -2.5, 0xff8800), true/yes and false/no become booleans, [a, b] becomes a list, and anything else is text: label=Speed (m/s) works. A comma or an unbalanced ) would end the value early, so the error says to quote it.

Names a pragma writes into the code, such as a slot ref, a hook handler or an import name, must be valid JavaScript names.

Named constants make a script readable, and the preprocessor removes them before it runs.

Orbit.jx
#define RADIUS 3
#define HEIGHT 1.5
#define TURNS_PER_SECOND 0.25
#pragma lifecycle(update)
function update(dt, time) {
const angle = time * TURNS_PER_SECOND * M_TAU;
self.parent.position.set(Math.cos(angle) * RADIUS, HEIGHT, Math.sin(angle) * RADIUS);
}

How it works:

  • RADIUS, HEIGHT and TURNS_PER_SECOND are replaced by their values as whole words.
  • M_TAU is predefined: one full turn, so TURNS_PER_SECOND * M_TAU is the angle travelled each second.
  • update(dt, time) places the parent on a circle from the playing time.

Device flags drop the code a device does not need. Here a phone or headset spawns fewer decorations.

Decorations.jx
#if IS_MOBILE || IS_HEADSET
#define COUNT 20
#else
#define COUNT 80
#endif
#pragma lifecycle(startup)
function startup() {
for (let i = 0; i < COUNT; i++) {
spawn('Flower', {
position: { x: Random.range(-10, 10), y: 0, z: Random.range(-10, 10) },
enabled: true,
});
}
log('Spawned', COUNT, 'flowers on', __FILE__);
}

How it works:

  • The #if keeps exactly one #define COUNT, chosen when the device loads the script.
  • spawn('Flower', …) copies an entity named Flower already in the scene; enabled: true switches the copy on even when the template is saved disabled.
  • __FILE__ is replaced by the name of the Behavior entity, handy in log lines.

A macro that logs an expression and its value, which you switch off in one line before publishing.

Tracker.jx
#define DEBUG 1
#if DEBUG
#define TRACE(x) log(#x, '=', x)
#else
#define TRACE(x) undefined
#endif
#pragma lifecycle(startup, update)
let target = null;
function startup() {
target = findEntity('Player');
ASSERT(target != null)
TRACE(target.name);
TRACE(target.position.y.toFixed(2));
}
function update(dt) {
self.parent.lookAt(target.position);
}

How it works:

  • #x turns the macro’s argument into its own source text, so the first log reads target.name = Player.
  • Setting DEBUG to 0 makes every TRACE(...) expand to a statement that does nothing, and the values are never computed.
  • ASSERT(target != null) stops the script with a clear message if the scene has no Player entity.

When the choice depends on something only known while running, use the Device global instead of a flag.

XRHint.jx
#pragma lifecycle(startup)
async function startup() {
if (Device.isHeadset()) {
log('Running in a headset browser');
return;
}
const vr = await Device.supportsImmersiveVR();
if (vr) log('This device can enter VR');
else if (Device.isTouch()) log('Touch controls');
else log('Mouse and keyboard controls');
}

How it works:

  • Device.isHeadset() and Device.isTouch() answer at once.
  • Device.supportsImmersiveVR() returns a promise, so startup is async and awaits it.
  • One script handles every device, where flags would build a different script per device.

Definitions are not substituted inside pragmas.

Wrong
#define MAX_SPEED 8
#pragma slot(ref=speed, type=Slider, min=0, max=MAX_SPEED)
Right
#pragma slot(ref=speed, type=Slider, min=0, max=8)
Wrong
const door = findEntity('Door');
ASSERT(door) // does not throw when door is undefined
Right
const door = findEntity('Door');
ASSERT(door != null)
Wrong
#define SPEED 2
#define SPEED 4
Right
#define SPEED 2
#undef SPEED
#define SPEED 4