Skip to content

Server Scripting Guide

coyotte508 edited this page Nov 11, 2013 · 7 revisions

Scripting/Server/Guide When you enter the initial evaluation, the last statement is returned to the scriptengine and used as the script object.

Here is an example script that does nothing but shows the recommended base for further scripting:

({

});

Another possible method is to use a closure:

(function(){
return ({

});
})();

Because closures can be difficult to debug you may want to avoid them.

The returned object is always accessible through the global script.

To add a simple event, such as when a user logs in, to greet them:

({
    afterLogIn: function (src) 
    {
        sys.sendAll("Hello " + sys.name(src) + ", how are you?")
    }
});

And a farewell:

({
    afterLogIn: function (src) 
    {
        sys.sendAll("Script: Hello " + sys.name(src) + ", how are you?");
    }
    ,
    beforeLogOut: function(src)
    {
        sys.sendAll("Script: Goodbye " + sys.name(src));
    } 
});

It is recommended you avoid using globals, as there is no downside to avoiding them and potential upsides, this means to put all code inside the script object.

({
    counter: 0
    ,
    afterLogIn: function (src) 
    {
        sys.sendAll("Script: Hello " + sys.name(src) + ", how are you?");
        this.counter++;
        sys.sendAll("You are the " + this.counter + (["th", "st","nd","rd"][this.counter] || "th") + " person to log in this script run!");
    }
    ,
    beforeLogOut: function(src)
    {
        sys.sendAll("Script: Goodbye " + sys.name(src));
    } 
});

It is recommended when your script becomes large, to separate into multiple files and use sys.import or sys.exec to include more files.

scripts.js

({
    counter: 0
    ,
    afterLogIn: function (src) 
    {
        sys.sendAll("Script: Hello " + sys.name(src) + ", how are you?");
        sys.sendAll("You are the " + this.utilities.formatNth(++this.counter) + " person to log in this script run!");
    }
    ,
    beforeLogOut: function(src)
    {
        sys.sendAll("Script: Goodbye " + sys.name(src));
    }
    ,
    utilities: sys.exec("utilities.js")
});

utilities.js

({
    formatNth: function (num)
    {
        return num.toString() + (["th", "st","nd","rd"][num] || "th");
    }
});

You could also do this dynamically by using script[name] = sys.exec(name + ".js") etc.