Autonum - guiled/LRE GitHub Wiki
Automatic number conversion
LRE allows you to automatically convert component values and table data to number when they are numeric by setting lre.autoNum(true)
in your system script.
Problem description
The following code used on Let's Role script raises a difficulty :
const bonusStrength = 1;
log('Base strength = ' + sheet.get('strength').value());
log('Total strength = ' + (sheet.get('strength').value() + bonusStrength));
/* log output example
Base strength = 12
Total strength = 121
*/
The bonus
should be mathematically added to the strength
component value but we can see that it is concatenated.
One common way to prevent this problem is to add parseInt()
functions or Number
API everywhere it is needed. The previous code is fixed as followed
const bonusStrength = 1;
log('Base strength = ' + sheet.get('strength').value());
log('Total strength = ' + (parseInt(sheet.get('strength').value()) + bonusStrength));
/* log output example
Base strength = 12
Total strength = 13
*/
This simple solution makes the code a little harder to read and some exhaustive systems have dozens of parseInt
in their script. Moreover you can lose time coding and debugging your system because you forgot to add parseInt
.
An example of parseInt forest in D&D4 system :
We can notice the same problem with table data. The following code shows that table data are always strings. (notice the double-quotes around the numbers that mean val
is a string)
Tables.get('test').each(log);
/*
Log output :
Object { id: "1", val: "42" }
Object { id: "2", val: "2.3" }
Object { id: "3", val: "23E2D" }
*/
lre.autoNum(true)
LRE solution = LRE offers a flag that allows you to automatically have a number value
when it is a numeric value (a string containing a number) in the component. This works for integer and decimal numbers. So you don't need to use parseInt
, parseFloat
or Number
anymore.
lre.autoNum
is set to false
by default and can be changed anywhere in your system code. Please note that any code run before lre.autoNum(true)
won't have any automatic conversions.
const init = lre(function (sheet) {
lre.autoNum(true);
const bonusStrength = 1;
log('Base strength = ' + sheet.get('strength').value());
log('Total strength = ' + (sheet.get('strength').value() + bonusStrength));
/* log output example
Base strength = 12
Total strength = 13
*/
};
The flag allows to automatically convert to number the table data as well. The following code from a previous example shows how the data is converted to number when possible. (you can notice in the log output that double-quotes are no more around values of val
because they are real numbers and not string anymore ; this happens only when possible as you can see for the third data that keeps being a string)
lre.autoNum(true);
Tables.get('test').each(log);
/*
Log output :
Object { id: 1, val: 42 }
Object { id: 2, val: 2.3 }
Object { id: 3, val: "23E2D" }
*/