ClientScripts and Channel¶
ClientScripts¶
server.clientScripts: JavaScript every
player's game runs, in a sandbox. See Client API
for what scripts can do.
Scripts run in the order they were first added. Replacing or removing one runs them all again from scratch.
set(name, code)¶
Adds a script, or replaces the one with that name, for everyone now and as they join.
| Parameter | Type | Description |
|---|---|---|
name |
string |
1-64 characters. |
code |
string |
JavaScript, up to 1 MB. |
Throws RangeError for a bad name.
setFile(path, name?)¶
Adds a script from a file on the server. It's sent to each player as they
join; prefer useClientFile for anything big.
| Parameter | Type | Description |
|---|---|---|
path |
string |
A file on the server. |
name |
string |
Default: the file's name. |
useClientFile(path)¶
Uses a client file as a script, named after its path. Players already have it, so only the name is sent.
| Parameter | Type | Description |
|---|---|---|
path |
string |
The client file's path. |
Throws Error if there's no such client file.
delete(name), has(name), names¶
Removes a script from everyone's game; whether one exists; and every script's name in the order they run.
Channel¶
server.channel(name): a named channel to and
from client scripts, carrying anything JSON can hold (up to 256 KB a
message). In client scripts it's sagl.on(name, fn) and
sagl.emit(name, data).
on(handler)¶
Handles what players' client scripts send on this channel.
| Parameter | Type | Description |
|---|---|---|
handler |
function |
Gets the player and the parsed data. |
server.channel("shop").on((player, data) => {
const { buy } = data as { buy: string };
if (buy === "armour" && player.money >= 100) {
player.giveMoney(-100);
player.armour = 100;
}
});
off(handler)¶
send(player, data?)¶
To one player's client scripts.
| Parameter | Type | Description |
|---|---|---|
player |
Player |
Who to. |
data |
unknown |
JSON-serialisable. |
Throws TypeError if data can't be serialised.
broadcast(data?)¶
To every player's client scripts.