We often need a single numerical variable that is not tied to a specific objective. For example:
  • A counter that goes from a number to another.
  • A numberOfEntities variable that counts the number of entities in the game.
With Sandstone, directly write those variables without creating any objective nor writing any command manually.


To create a variable, the following syntax can be used:
import { Variable } from 'sandstone'

// Create a variable initialized to 0
const myCounter = Variable(0)

// Create a variable that isn't initialized
const numberOfEntities = Variable()
Variables are Score instances. You can use all their methods, including all operations and comparisons.
There are two kind of variables: global variables, and scoped variables.

Global variables

Global variables are declared outside MCFunctions. They will be initialized when the data pack loads. If an initial value has been given, the variable will be set to this value each time the data pack loads.
// The number of entities will be set to 0 when the datapack loads
const numberOfEntities = Variable(0)

Scoped variables

Scoped variables are declared inside a given MCFunction. Each time the function is called, the variable will be initialized and set to its initial value (if any).
MCFunction('count_diamonds', () => {
  // This will be set to 0 each time the function is called
  const totalDiamonds = Variable(0)

  execute.as('@a').run(() => {
		// This variable has no initialization
    const myDiamonds = Variable()

    // Store the number of diamonds the player has in `myDiamonds`
    execute.store.result.score(myDiamonds).run.clear('@s', 'minecraft:diamonds', 0)

    // Add user diamonds to the total

	// Display the result
  tellraw('@a', ['The total number of diamonds is ', totalDiamonds])