Difference between revisions of "Sheet Worker Snippets"
From Roll20 Wiki
Andreas J. (Talk | contribs) m (→See Also) |
Andreas J. (Talk | contribs) m |
||
Line 1: | Line 1: | ||
''Main Article:'' '''[[Sheet Worker Scripts]]''' {{NavSheetDoc}} | ''Main Article:'' '''[[Sheet Worker Scripts]]''' {{NavSheetDoc}} | ||
+ | |||
+ | Short code snippets to be used. See Also: [[Sheetworker_examples_for_Non-programmers|Sheetworker Examples for Non-programmers]] | ||
<br> | <br> | ||
=Examples= | =Examples= |
Revision as of 17:48, 17 April 2021
Main Article: Sheet Worker ScriptsCharacter Sheet Development
Getting Started
- Using Custom Sheets
- Building Sheets
(Main Page) - Glossary
- Code Restrictions
- Best Practice
- Common Mistakes
- Tutorials
- Examples, Templates
- Pattern Libraries
- HTML & storing data
- CSS & Styling
General
- Updates & Changelog
- Known Bugs
- Character Sheet Enhancement(CSE)
- Custom Roll Parsing
- Legacy Sheet(LCS)
- Beacon SDK
Reference
- Buttons
- Repeating Sections
- Sheetworkers
- Roll Templates
- sheet.json
- Translation
- Auto-Calc
- Advanced
- All SheetDev Pages
Tools & Tips
Other
Short code snippets to be used. See Also: Sheetworker Examples for Non-programmers
Contents |
Examples
Auto-calculating Attributes
Example 1
(credit: Rabulias)
Your best bet would be to avoid the autocalc fields entirely if you can. Monitor the two other fields and when they change, have a sheetworker that adds them up to the new value. Then you can refer to the new value in other calculations much easier.
on("sheet:opened change:stat_a change:stat_b", function() { getAttrs(["stat_a", "stat_b"], function(values) { setAttrs({ "foo_modchars": parseInt(values["stat_a"]) || 0 + parseInt(values["stat_b"]) || 0 }); }); });
Example 2
(credit: GiGs)
I remember seeing a script someone wrote to allow you to use autocalc fields within sheet workers, but it's just simpler to use Rabulias's approach(see example 1 above).
Add the relevant stats to the on(change:) line, and duplicate the calculation within the sheet worker.
I generally don't put my working in the setattrs call, but before it so i can more easily check it. Something like
on("sheet:opened change:stat_a change:stat_b", function() { getAttrs(["stat_a", "stat_b"], function(values) { var stat_a = parseInt(values["stat_a"])||0; var stat_b = parseInt(values["stat_b"])||0; var output = stat_a + stat_b; setAttrs({ "foo_modchars": output }); }); });
Helper Functions
This section is for useful functions that aren't complete sheet workers, but are useful to use in sheet workers.
Function: parseValues
(credit: GiGs) Many sheet workers have a bunch of lines like this:
var stat_a = parseInt(values["stat_a"])||0; var stat_b = parseInt(values["stat_b"])||0;
You might also have lines like this:
setAttrs({ "foo_modchars": parseInt(values["stat_a"],10) || 0 + parseInt(values["stat_b"],10) || 0 });
It gets tedious typing out all that. With the function below, you would instead write them as:
var stat_a = parseValues(values,"stat_a"); var stat_b = parseValues(values,"stat_b"); setAttrs({ "foo_modchars": parseValues(values,"stat_a") + parseValues(values,"stat_b") });
I think that's a lot easier to read. Here's the function:
parseValues
Place this at the start of your script block, and you'll be able to use it in all your sheet workers.
const parseValues = (values, stat, type='int') => { if(type === 'int') return parseInt(values[stat])||0; else if(type === 'float') return parseFloat(values[stat])||0; else if(type === 'str') return values[stat]; };
By default, it returns an integer. If you call it with a second parameter, it will return either a float or a string:
-
parseValues(values, stat)
orparseValues(values, stat, 'int')
- returns an integer. -
parseValues(values, stat,'float')
- returns a Float (a number that is not an integer) -
parseValues(values, stat, 'str')
- returns the value as text. (Not really needed!)
This function does handle variable attribute names. If you were in a loop and creating attributes like, "stat" + i it will work fine.
Reuse of fields for listeners
(credit: Marco G.)
In order to prevent typing the same thing over and over again you can store the fields that you want to use in an array and reuse it for event listeners and getAttrs.
It will looks like this:
let fields = ["str", "dex", "con"]; on(fields.map(field => "change:" + field).join(" "), () => { getAttrs(fields, (values ) => { .... }); });
Repeating Section
Example 1
Example of how to edit stats within a repeated section. sourc(Forum)
// this is wrapped inside a repeating section that is called "repeating_psychicabilities" <input class='hidden' type='text' name='attr_psy_ab_total_finder' readonly /> <input class='hidden' type='text' name='attr_psy_ab_unnat_finder' readonly /> <select name='attr_P_focus' class=''> <option value='wp' selected='selected'>Willpower</option> <option value='per'>Perception</option> <option value='psyniscience'>Psyniscience</option> </select>
on('sheet:opened change:repeating_psychicabilities:p_focus', function() { getSectionIDs('psychicabilities', function(idarray) { // first get the attribute names for all rows in put in one array const fieldnames = []; idarray.forEach(id => fieldnames.push(`repeating_psychicabilities_${id}_P_focus`)); getAttrs(fieldnames, values => { // create a variable to hold all the attribute values you re going to create. const attr = {}; // now loop through the rows again idarray.forEach(id => { let row = 'repeating_psychicabilities_' + id; let p_focus = values[`${row}_P_focus`] || wp; if (p_focus.length > 3) { attr[`${row}_psy_ab_total_finder`] = `@{${p_focus}_total}`; attr[`${row}_psy_ab_unnat_finder`] = `@{${p_focus}_unnat}`; } else { attr[`${row}_psy_ab_total_finder`] = `@{${p_focus}Total}`; attr[`${row}_psy_ab_unnat_finder`] = `@{${p_focus.toUpperCase()}_unnat}`; } }); console.log(values,attr) setAttrs(attr); }); }); });
Related Pages
- List of all Sheetworker-articles
- Sheetworker Examples for Non-programmers
- Universal Sheet Workers - How to create one function that can handle a bunch of similar sheet workers
- The RepeatingSum Function - How to add up the weight of all items in a repeating section
See Also
- Sheet Worker Optimization(Forum) by Scott C.
- How to integrate table of stats into a sheet(Forum) by GiGs
- Multiversal Sheetworker Generator(Forum) by GiGs
- Introduction to JavaScript - MDN web docs
- JavaScript Best Practices - MDN web docs