FirstScript
Introduction
Writing a script while you're not a coder is a very intimidating task : it is a new language with a lot of syntax rules.
You can start reading some tutorials on how to start with javascript. Let's Role allows you to code with a version of JavaScript that is close to the standard, but with a few differences.
Step 0 : basics
Here are a list of empiric rules that will help you writing your script :
- make it readable and understandable : use appropriate names, indent your code (format your code automaticaly with
SHIFT+ALT+F) - structure, separate your rules
- don't repeat yourself (DRY) : there are many ways to make your code readable and not repetitive. Remind one rule : if you copy / paste some code in your script, it could good to generalise it.
- Don't hesitate to ask the community for help
Step 1 : init
Every script must have a init function. This function will be called as soon as a sheet is opened (character sheet, token sheet, craft sheet, prompt sheet). We use the init to add some interactivity and complex rules on the sheet.
As it is a unique function to handle many different sheets, you must use an if to check which init code to execute on which sheet.
Here is a simple example that we recommend to use only if you plan to keep the very simple script.
init = function (sheet) {
if (sheet.id() === "main") {
// write you code here for the sheet with the id "main"
}
}
If you want to make some inits for few other sheets, we recommend to create different function. The following solution is a very clean way to handle the initialisation of different sheets using their id to detect them. Creating different function helps you to separate the rules of your system. The more your script will grow, the more you'll need to organize it.
init = function (sheet) {
const sheetId = sheet.id()
if (sheetId === "main") {
initMain(sheet)
} else if (sheetId === "monster") {
initMonster(sheet)
} else if (sheetId === "object") {
initObject(sheet)
}
}
function initMain(sheet) {
// write you code here for the sheet with the id "main"
}
function initMonster(sheet) {
// write you code here for the sheet with the id "monster"
}
function initObject(sheet) {
// write you code here for the sheet with the id "object"
}
As the number of pages increases, you will quickly see that you are repeating yourself by adding a long list of if else if, to prevent that you can check this advanced script tip for init.