Sharing code between resources
A resource can offer values and functions to other resources on the same side: server to server,
or client to client. Nothing goes over the network, and live functions and objects cannot cross it.
To reach the other side, use Events.
Offering something
First list the names in your manifest under kcds.exports:
{
"name": "library",
"kcds": {
"serverScripts": ["server.js"],
"exports": ["config", "pay"]
}
}Then register them:
const { Exports } = kcds.core; Exports.register('config', { currency: 'groschen' }); Exports.register('pay', (amount) => amount - 1);
Exports.register always returns true. A name missing from the manifest is not stored, and a
warning goes to the log. Registering a listed name again overwrites its value.
Using it
The other resource lists yours under kcds.requires, which also makes yours start first:
{
"name": "shop",
"kcds": {
"serverScripts": ["server.js"],
"requires": ["library"]
}
}If the server may not have the other resource, mark it optional with { "name": "library", "optional": true }. It starts first when present, and yours starts without it otherwise.
const { Exports, Imports } = kcds.core; const pay = Exports.get('library', 'pay'); const afterFee = pay(100); const everything = Imports.get('library'); // { config, pay }
Exports.get(resource, name)returns one value.Imports.get(resource)returns a new object with all of that resource's current exports, or{}if it has none.
Shared, not copied
You receive the same object the other resource holds, so a change made by anyone is seen by everyone. For that reason, a library should offer functions instead of data others can change.
When something is wrong
| Situation | Result |
|---|---|
| The name does not exist | throws Export not found |
| The resource is not running | throws Resource is not available |
The resource is not in your requires | a warning in the log, once for each resource you read |
Listing a link as optional also removes that warning.
Restarts
Exports are a local list, so reading one sends no request to the server or game. When a resource
stops, its exports disappear. ensure <name> restarts the resource and the running resources that
depend on it, and the old values are gone, so read your imports again after a restart.
If you want looser coupling, with a request and a reply, see Messages.