Foundry Virtual Tabletop - API Documentation - Version 14
    Preparing search index...

    Class Roll

    An interface and API for constructing and evaluating dice rolls. The basic structure for a dice roll is a string formula and an object of data against which to parse it.

    // Construct the Roll instance
    let r = new Roll("2d20kh + @prof + @strMod", {prof: 2, strMod: 4});

    // The parsed terms of the roll formula
    console.log(r.terms); // [Die, OperatorTerm, NumericTerm, OperatorTerm, NumericTerm]

    // Execute the roll
    await r.evaluate();

    // The resulting equation after it was rolled
    console.log(r.result); // 16 + 2 + 4

    // The total resulting from the roll
    console.log(r.total); // 22
    Index

    Constructors

    • Parameters

      • formula: string = ""

        The string formula to parse

      • data: object = {}

        The data object against which to parse attributes within the formula

      • Optionaloptions: RollOptions = {}

        Options modifying or describing the Roll

      Returns Roll

    Properties

    _dice: DiceTerm[] = []

    An array of inner DiceTerms that were evaluated as part of the Roll evaluation

    _evaluated: boolean = false

    Track whether this Roll instance has been evaluated or not. Once evaluated the Roll is immutable.

    _formula: string

    Store the original cleaned formula for the Roll, prior to any internal evaluation or simplification

    _resolver: RollResolver

    A reference to the RollResolver app being used to externally resolve this Roll.

    _root: Roll

    A reference to the Roll at the root of the evaluation tree.

    _total: number

    Cache the numeric total generated through evaluation of the Roll.

    data: object

    The original provided data object which substitutes into attributes of the roll formula.

    options: RollOptions

    Options modifying or describing the Roll

    terms: RollTerm[]

    The identified terms of the Roll

    CHAT_TEMPLATE: string = "templates/dice/roll.hbs"

    The HTML template path used to render a complete Roll object to the chat log

    DICE_CONFIGURATION_SETTING: "diceConfiguration"

    Dice Configuration setting name.

    MATH_PROXY: Math = ...

    A Proxy environment for safely evaluating a string using only available Math functions

    RESOLVERS: Map<Roll, RollResolver> = ...

    A mapping of Roll instances to currently-active resolvers.

    TOOLTIP_TEMPLATE: string = "templates/dice/tooltip.hbs"

    The HTML template used to render an expanded Roll tooltip to the chat log

    Accessors

    • get dice(): DiceTerm[]

      Return an Array of the individual DiceTerm instances contained within this Roll.

      Returns DiceTerm[]

    • get formula(): string

      Return a standardized representation for the displayed formula associated with this Roll.

      Returns string

    • get isDeterministic(): boolean

      Whether this Roll contains entirely deterministic terms or whether there is some randomness.

      Returns boolean

    • get product(): any

      Return the arbitrary product of evaluating this Roll.

      Returns any

    • get result(): string

      The resulting arithmetic expression after rolls have been evaluated

      Returns string

    • get total(): number

      Return the total result of the Roll expression if it has been evaluated.

      Returns number

    • get defaultImplementation(): typeof Roll

      Get the default configured Roll class.

      Returns typeof Roll

    • get resolverImplementation(): typeof RollResolver

      Retrieve the appropriate resolver implementation based on the user's configuration.

      Returns typeof RollResolver

    Methods

    • Alter the Roll expression by adding or multiplying the number of dice which are rolled

      Parameters

      • multiply: number

        A factor to multiply. Dice are multiplied before any additions.

      • add: number

        A number of dice to add. Dice are added after multiplication.

      • OptionalmultiplyNumeric: boolean = {}

        Apply multiplication factor to numeric scalar terms

      Returns Roll

      The altered Roll expression

    • Clone the Roll instance, returning a new Roll instance that has not yet been evaluated.

      Returns Roll

    • Execute the Roll asynchronously, replacing dice and evaluating the total result

      Parameters

      • Optionaloptions: {
            allowInteractive?: boolean;
            allowStrings?: boolean;
            maximize?: boolean;
            minimize?: boolean;
        } = {}

        Options which inform how the Roll is evaluated

        • OptionalallowInteractive?: boolean

          If false, force the use of non-interactive rolls and do not prompt the user to make manual rolls.

        • OptionalallowStrings?: boolean

          If true, string terms will not cause an error to be thrown during evaluation.

        • Optionalmaximize?: boolean

          Maximize the result, obtaining the largest possible value.

        • Optionalminimize?: boolean

          Minimize the result, obtaining the smallest possible value.

      Returns Promise<Roll>

      The evaluated Roll instance

      let r = new Roll("2d6 + 4 + 1d4");
      await r.evaluate();
      console.log(r.result); // 5 + 4 + 2
      console.log(r.total); // 11
    • Execute the Roll synchronously, replacing dice and evaluating the total result.

      Parameters

      • Optionaloptions: {
            allowStrings?: boolean;
            maximize?: boolean;
            minimize?: boolean;
            strict?: boolean;
        } = {}
        • OptionalallowStrings?: boolean

          If true, string terms will not cause an error to be thrown during evaluation.

        • Optionalmaximize?: boolean

          Maximize the result, obtaining the largest possible value.

        • Optionalminimize?: boolean

          Minimize the result, obtaining the smallest possible value.

        • Optionalstrict?: boolean

          Throw an Error if the Roll contains non-deterministic terms that cannot be evaluated synchronously. If this is set to false, non-deterministic terms will be ignored.

      Returns Roll

      The evaluated Roll instance.

    • Render the tooltip HTML for a Roll instance

      Returns Promise<string>

      The rendered HTML tooltip as a string

    • Propagate flavor text across all terms that do not have any.

      Parameters

      • flavor: string

        The flavor text.

      Returns void

    • Render a Roll instance to HTML

      Parameters

      • Optionaloptions: { flavor?: string; isPrivate?: boolean; template?: string } = {}

        Options which affect how the Roll is rendered

        • Optionalflavor?: string

          Flavor text to include

        • OptionalisPrivate?: boolean

          Is the Roll displayed privately?

        • Optionaltemplate?: string

          A custom HTML template path

      Returns Promise<string>

      The rendered HTML template as a string

    • Create a new Roll object using the original provided formula and data. Each roll is immutable, so this method returns a new Roll instance using the same data.

      Parameters

      • Optionaloptions: object = {}

        Evaluation options passed to Roll#evaluate

      Returns Promise<Roll>

      A new Roll object, rolled using the same formula and data

    • Recompile the formula string that represents this Roll instance from its component terms.

      Returns string

      The re-compiled formula

    • Alias for evaluate.

      Parameters

      • options: object = {}

        Options passed to Roll#evaluate

      Returns Promise<Roll>

    • Construct an inline roll link for this Roll.

      Parameters

      • Optionaloptions: {
            attrs?: Record<string, string>;
            classes?: string[];
            dataset?: Record<string, string>;
            icon?: string;
            label?: string;
        } = {}

        Additional options to configure how the link is constructed.

        • Optionalattrs?: Record<string, string>

          Attributes to set on the link.

        • Optionalclasses?: string[]

          Additional classes to add to the link. The classes inline-roll and inline-result are added by default.

        • Optionaldataset?: Record<string, string>

          Custom data attributes to set on the link.

        • Optionalicon?: string

          A font-awesome icon class to use as the icon instead of a d20.

        • Optionallabel?: string

          A custom label for the total.

      Returns HTMLAnchorElement

    • Represent the data of the Roll as an object suitable for JSON serialization.

      Returns object

      Structured data which can be serialized into JSON

    • Transform a Roll instance into a ChatMessage, displaying the roll result. This function can either create the ChatMessage directly, or return the data object that will be used to create.

      Parameters

      • messageData: object = {}

        The data object to use when creating the message

      • Optionaloptions: { create?: boolean; messageMode?: string } = {}

        Additional options which modify the created message.

        • Optionalcreate?: boolean

          Whether to automatically create the chat message, or only return the prepared chatData object.

        • OptionalmessageMode?: string

          A message visibility mode to apply to the resulting message.

      Returns Promise<any>

      A promise which resolves to the created ChatMessage document if create is true, or the Object of prepared chatData otherwise.

    • Returns string

    • Protected

      Evaluate the roll asynchronously.

      Parameters

      • Optionaloptions: {
            allowInteractive?: boolean;
            allowStrings?: boolean;
            maximize?: boolean;
            minimize?: boolean;
        } = {}

        Options which inform how evaluation is performed

        • OptionalallowInteractive?: boolean

          If false, force the use of digital rolls and do not prompt the user to make manual rolls.

        • OptionalallowStrings?: boolean

          If true, string terms will not cause an error to be thrown during evaluation.

        • Optionalmaximize?: boolean

          Force the result to be maximized

        • Optionalminimize?: boolean

          Force the result to be minimized

      Returns Promise<Roll>

    • Protected

      Evaluate an AST asynchronously.

      Parameters

      • node: RollParseNode | RollTerm

        The root node or term.

      • Optionaloptions: { allowStrings?: boolean; maximize?: boolean; minimize?: boolean } = {}

        Options which inform how evaluation is performed

        • OptionalallowStrings?: boolean

          If true, string terms will not cause an error to be thrown during evaluation.

        • Optionalmaximize?: boolean

          Force the result to be maximized

        • Optionalminimize?: boolean

          Force the result to be minimized

      Returns Promise<string | number>

    • Protected

      Evaluate an AST synchronously.

      Parameters

      • node: RollParseNode | RollTerm

        The root node or term.

      • Optionaloptions: {
            allowStrings?: boolean;
            maximize?: boolean;
            minimize?: boolean;
            strict?: boolean;
        } = {}

        Options which inform how evaluation is performed

        • OptionalallowStrings?: boolean

          If true, string terms will not cause an error to be thrown during evaluation.

        • Optionalmaximize?: boolean

          Force the result to be maximized

        • Optionalminimize?: boolean

          Force the result to be minimized

        • Optionalstrict?: boolean

          Throw an error if encountering a term that cannot be synchronously evaluated.

      Returns string | number

    • Protected

      Evaluate the roll synchronously.

      Parameters

      • Optionaloptions: {
            allowStrings?: boolean;
            maximize?: boolean;
            minimize?: boolean;
            strict?: boolean;
        } = {}

        Options which inform how evaluation is performed

        • OptionalallowStrings?: boolean

          If true, string terms will not cause an error to be thrown during evaluation.

        • Optionalmaximize?: boolean

          Force the result to be maximized

        • Optionalminimize?: boolean

          Force the result to be minimized

        • Optionalstrict?: boolean

          Throw an error if encountering a term that cannot be synchronously evaluated.

      Returns Roll

    • Protected

      Safely evaluate the final total result for the Roll using its component terms.

      Returns number

      The evaluated total

    • Protected

      Prepare context data used to render the CHAT_TEMPLATE for this roll.

      Parameters

      • options: { flavor?: string; isPrivate?: boolean } = {}

      Returns Promise<{ object: any }>

    • Protected

      Prepare the data structure used for the Roll. This is factored out to allow for custom Roll classes to do special data preparation using provided input.

      Parameters

      • data: object

        Provided roll data

      Returns object

      The prepared data object

    • Internal

      Classify a remaining string term into a recognized RollTerm class

      Parameters

      • term: string

        A remaining un-classified string

      • Optionaloptions: { intermediate?: boolean; next?: string | RollTerm; prior?: string | RollTerm } = {}

        Options which customize classification

        • Optionalintermediate?: boolean

          Allow intermediate terms

        • Optionalnext?: string | RollTerm

          The next term to classify

        • Optionalprior?: string | RollTerm

          The prior classified term

      Returns RollTerm

      A classified RollTerm instance

    • Map a legacy rollMode into a message mode string.

      Parameters

      • rollMode: string

      Returns string

      since v14

    • Collapse an expanded inline roll to conceal its tooltip.

      Parameters

      • a: HTMLAnchorElement

        The inline-roll button

      Returns void

    • A factory method which constructs a Roll instance using the default configured Roll class.

      Parameters

      • formula: string

        The formula used to create the Roll instance

      • Optionaldata: object = {}

        The data object which provides component data for the formula

      • Optionaloptions: object = {}

        Additional options which modify or describe this Roll

      Returns Roll

      The constructed Roll instance

    • Expand an inline roll element to display its contained dice result as a tooltip.

      Parameters

      • a: HTMLAnchorElement

        The inline-roll button

      Returns Promise<void>

    • Recreate a Roll instance using a provided data object

      Parameters

      • data: object

        Unpacked data representing the Roll

      Returns Roll

      A reconstructed Roll instance

    • Recreate a Roll instance using a provided JSON string

      Parameters

      • json: string

        Serialized JSON data representing the Roll

      Returns Roll

      A reconstructed Roll instance

    • Manually construct a Roll object by providing an explicit set of input terms

      Parameters

      • terms: RollTerm[]

        The array of terms to use as the basis for the Roll

      • Optionaloptions: object = {}

        Additional options passed to the Roll constructor

      Returns Roll

      The constructed Roll instance

      const t1 = new Die({number: 4, faces: 8};
      const plus = new OperatorTerm({operator: "+"});
      const t2 = new NumericTerm({number: 8});
      const roll = Roll.fromTerms([t1, plus, t2]);
      roll.formula; // 4d8 + 8
    • Transform an array of RollTerm objects into a cleaned string formula representation.

      Parameters

      • terms: RollTerm[]

        An array of terms to represent as a formula

      Returns string

      The string representation of the formula

    • Determine which of the given terms require external fulfillment.

      Parameters

      Returns DiceTerm[]

    • Parse a formula expression using the compiled peggy grammar.

      Parameters

      • formula: string = ""

        The original string expression to parse.

      • data: object = {}

        A data object used to substitute for attributes in the formula.

      Returns RollTerm[]

    • Register an externally-fulfilled result with an active RollResolver.

      Parameters

      • method: string

        The fulfillment method.

      • denomination: string

        The die denomination being fulfilled.

      • result: number

        The obtained result.

      Returns boolean | void

      Whether the result was consumed. Returns undefined if no resolver was available.

    • Replace referenced data attributes in the roll formula with values from the provided data. Data references in the formula use the @attr syntax and would reference the corresponding attr key.

      Parameters

      • formula: string

        The original formula within which to replace

      • data: object

        The data object which provides replacements

      • Optionaloptions: ReplaceFormulaDataOptions = {}

        Options which modify formula replacement

      • _r: number = 0

        An internal recursion tracker

      Returns string

    • A sandbox-safe evaluation function to execute user-input code with access to scoped Math methods.

      Parameters

      • expression: string

        The input string expression

      Returns number

      The numeric evaluated result

    • After parenthetical and arithmetic terms have been resolved, we need to simplify the remaining expression. Any remaining string terms need to be combined with adjacent non-operators in order to construct parsable terms.

      Parameters

      • terms: RollTerm[]

        An array of terms which is eligible for simplification

      Returns RollTerm[]

      An array of simplified terms

    • Simulate a roll and evaluate the distribution of returned results

      Parameters

      • formula: string

        The Roll expression to simulate

      • n: number = 10000

        The number of simulations

      Returns Promise<number[]>

      The rolled totals

    • Validate that a provided roll formula can represent a valid

      Parameters

      • formula: string

        A candidate formula to validate

      Returns boolean

      Is the provided input a valid dice formula?