Wiki 9Minecraft Wiki 9Minecraft

Molang Expressions Reference

Embed dynamic math, state queries, and logic directly inside your resource and behavior JSON files.

5Sections
3Code examples
4Known errors

Molang is a fast, lightweight expression language built into Minecraft Bedrock Edition. Creators use it to calculate dynamic values on the fly, bridging the gap between static JSON definitions and live game states. You will reach for Molang whenever you need a bone to rotate with a mob's walking speed, a render controller to swap textures based on entity variants, or a behavior filter to check conditions before firing an event.

Core Syntax and Data Types

At its core, Molang only deals with floating-point numbers. Even boolean logic is represented numerically: a value of 0.0 is evaluated as false, while any non-zero value (typically 1.0) is evaluated as true. Some specific resource pack fields also accept string literals enclosed in single quotes, such as when passing a particle or sound effect name, though you cannot perform string manipulation.

Expressions can be written as a single simple statement or chained together into a complex multi-statement block. Simple expressions implicitly return their evaluated result. When an expression contains multiple statements separated by semicolons, it is considered a complex expression. In complex expressions, you must explicitly use the return keyword at the end to output the final value, otherwise the expression will evaluate to 0.0.

RP/animations/custom_mob.animation.json
t.wave = math.sin(q.life_time * 120.0); t.dampen = q.is_on_ground ? 1.0 : 0.2; return t.wave * t.dampen * 15.0;

Prefixes, Queries, and Variables

Molang accesses game data and stores values using specific namespaces, each with a short alias to save space in JSON files. Queries read live state from the game engine and are strictly read-only. If you call a query that does not apply to the current actor, it typically defaults to 0.0.

Variables let you store your own numbers during evaluation. Temporary variables are the fastest and safest choice when a value is only needed inside a single formula. Regular variables persist on the entity for the duration of the current play session, allowing an animation controller to pass data over to a render controller. Remember that client-side resource pack variables and server-side behavior pack variables exist on separate threads and cannot read each other directly; to sync data across both sides, use entity properties instead.

PrefixShort AliasWhat it doesNotes
query.q.Reads live data from the entity or worldRead-only; arguments go in parentheses if required
variable.v.Reads or writes a value attached to the actorPersists across frames; does not save to disk on world reload
temp.t.Reads or writes a local, short-lived valueCleared immediately after the current expression finishes
context.c.Reads read-only data passed by a specific eventOnly available in certain contexts like item animations or loot
math.math.Calls a built-in mathematical functionNo single-letter alias; always write out math in full

Math Functions and Logic Operators

The math namespace provides standard arithmetic and trigonometric functions essential for procedural animations and custom particle motion. Crucially, all trigonometric functions in Bedrock Molang—such as math.sin and math.cos—operate in degrees, not radians. To make a bone complete one full oscillation per second, you multiply query.life_time by 360.0 inside a sine wave.

For conditional branching, Molang supports standard comparison operators alongside the ternary operator. You can write a ternary expression as condition ? value_if_true : value_if_false. You can also use a binary conditional without the colon, which simply executes the right side if the left side is true and returns 0.0 otherwise. For null-safety when checking variables that might not be initialized yet, the null-coalescing operator (??) returns the right-hand fallback value if the left-hand side is undefined.

FunctionWhat it doesNotes
math.sin(deg)Returns the sine of an angleInput angle is measured in degrees
math.cos(deg)Returns the cosine of an angleInput angle is measured in degrees
math.clamp(val, min, max)Restricts a value between two boundsUseful for capping rotation angles or speeds
math.lerp(start, end, zero_to_one)Linearly interpolates between start and endThe third argument blends from 0.0 (start) to 1.0 (end)
math.random(low, high)Generates a random float between low and highEvaluated every time the expression runs
math.floor(val)Rounds a float down to the nearest whole numberHandy for converting continuous timers into discrete steps

Using Molang in Resource Packs

Resource packs are the most common place to write Molang. In animation files, you replace static keyframe numbers with string expressions to drive bone position, rotation, and scale dynamically. A classic walk cycle uses query.modified_distance_moved to advance the phase of a wave and query.modified_move_speed to scale the amplitude, ensuring the legs stop swinging the exact moment the entity halts.

In render controllers, Molang selects which geometry, material, and texture to display from defined arrays. By defining an array of textures and indexing into it using an expression like Array.skins[query.variant], a single render controller can handle dozens of visual variations without duplicating files.

RP/animations/custom_mob.animation.json
{
  "format_version": "1.8.0",
  "animations": {
    "animation.custom_mob.walk": {
      "loop": true,
      "bones": {
        "left_leg": {
          "rotation": [
            "math.cos(q.modified_distance_moved * 38.17) * 40.0 * q.modified_move_speed",
            0.0,
            0.0
          ]
        },
        "right_leg": {
          "rotation": [
            "-math.cos(q.modified_distance_moved * 38.17) * 40.0 * q.modified_move_speed",
            0.0,
            0.0
          ]
        }
      }
    }
  }
}

Using Molang in Behavior Packs

On the server side, Molang is used inside entity definitions, block permutations, and item components. In entity JSON files, the scripts object inside the description block lets you run initialization expressions under the initialize key and frame-by-frame calculations under the animate key. You can also trigger behavior animation controllers from this exact same block.

Within component groups and events, the query_expression filter evaluates a Molang string to decide whether a component or event should activate. While legacy entity filters exist for many basic checks, query_expression allows you to combine multiple checks and math operations into a single compact line.

BP/entities/custom_mob.json
{
  "format_version": "1.20.80",
  "minecraft:entity": {
    "description": {
      "identifier": "custom:forest_spirit",
      "is_spawnable": true,
      "is_summonable": true,
      "scripts": {
        "initialize": [
          "v.attack_cooldown = 0.0;"
        ],
        "animate": [
          "controller_spirit_combat"
        ]
      },
      "animations": {
        "controller_spirit_combat": "controller.animation.spirit.combat"
      }
    },
    "components": {
      "minecraft:health": {
        "value": 20,
        "max": 20
      },
      "minecraft:environment_sensor": {
        "triggers": [
          {
            "filters": {
              "test": "is_daytime",
              "value": true
            },
            "event": "custom:start_fleeing"
          }
        ]
      }
    }
  }
}

Which versions this applies to

Applies to all modern Bedrock versions (1.16.0 through 1.21+). Core Molang is completely stable and requires no experimental toggles, though individual new queries introduced in recent game updates require matching the file format_version to the release that added them.

When it does not work

What you seeWhyThe fix
Content Log shows: [Molang][error]-Error: unhandled request for unknown variable 'v.my_var'You read a variable in an animation or render controller before it was given an initial value, often because the initialization script has not run yet or had a typo.Initialize the variable under scripts.initialize in the entity client_entity or server entity definition, or use the null-coalescing operator (v.my_var ?? 0.0) to provide a safe fallback.
A bone snaps to 0 rotation or an expression always evaluates to false despite using semicolons to compute intermediate values.Once you place a semicolon inside a Molang string, the parser treats it as a complex multi-statement expression. Complex expressions do not implicitly output their last line; they default to returning 0.0 unless instructed otherwise.Add the return keyword before the final calculation in your expression string, for example: 't.a = 5; return t.a * 2;'.
A variable set in a behavior pack animation controller reads as 0.0 inside a resource pack render controller.Variables prefixed with v. or variable. are isolated to the side that created them. Server-side behavior packs and client-side resource packs do not share their variable tables.Define an entity property in the behavior pack description and read it on both sides using query.property('namespace:prop_name').
JSON parser error on pack load when using && or || inside a Molang string.This usually happens when quotes or escape characters inside the JSON string are mismatched, or when a creator accidentally writes a single & or | (bitwise operators, which are not valid logical operators in Molang).Ensure you use double ampersands (&&) for logical AND and double pipes (||) for logical OR, and verify that the entire expression is wrapped in a single valid pair of double quotes for JSON.

Reference, straight from the game files

Read out of the game itself, so the ids match the version you are building for.