Sharing variables between scripts

setShared(key, value) Description: Stores a variable in a public list accessible by all scripts. Parameters:

  • key (String): The unique identifier for the variable.

  • value (Any): The value to be stored. This can be a string, number, object, function, list, class instance, etc.

getShared(key) Description: Retrieves a variable from the public list. If the variable does not exist, the function will wait until it does or timeout after 500 milliseconds. Parameters:

  • key (String): The unique identifier for the variable to be retrieved.

Returns:

  • The value associated with the given key, or null if the variable does not exist within the timeout period.

here are quick examples:

setShared("testVar", "Hello world!")

To read a public variable from any script do the following:

getShared("testVar")

It'll return the variable "Hello world!" You can share any type of variable! Here is an example with a function:

script1.js
var Bukkit = org.bukkit.Bukkit;

// Function to broadcast the total entity count
function broadcastEntityCount() {
    // Get the OpenJS plugin instance
    var plugin = Bukkit.getPluginManager().getPlugin("OpenJS");
 
    // Run the task asynchronously
    Bukkit.getScheduler().runTask(plugin, new java.lang.Runnable({
        run: function() {
            // Get the server and initialize entity count
            var server = plugin.getServer();
            var entityCount = 0;

            // Get all worlds on the server
            var worlds = server.getWorlds();
            for (var i = 0; i < worlds.size(); i++) {
                var world = worlds.get(i);
                // Add the number of entities in the current world to the total count
                entityCount += world.getEntities().size();
            }

            // Broadcast the total entity count to all players
            server.broadcastMessage("Total entities: " + entityCount);
        }
    }));
}

// Call the broadcastEntityCount function immediately
broadcastEntityCount();

// Set the broadcastEntityCount function as a public variable
setShared("broadcastEntities", broadcastEntityCount);
script2.js
// Retrieve the public variable "broadcastEntities" and store it in a variable
var broadcastEntitiesFunction = getShared("broadcastEntities");

// Call the broadcastEntitiesFunction
broadcastEntitiesFunction();
  • The getShared function will block and wait for up to 500 milliseconds for the variable to become available. If it doesn't become available within this time, it returns null.

  • These functions allow for inter-script communication and sharing of data, making it easier to modularize your code and keep scripts clean and focused.

Last updated