Jump to content
Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Module:Dice: Difference between revisions

From Teriock
// via Wikitext Extension for VSCode
 
// via Wikitext Extension for VSCode
Line 1: Line 1:
-- Module:Dice
-- Processes dice input strings and outputs HTML spans with roll links, templates, and data attributes
local p = {}
local p = {}
local html = mw.html


-- Helper function to trim whitespace
-- Trim whitespace from both ends
local function trim(s)
local function trim(s)
    return s:match("^%s*(.-)%s*$")
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end
 
-- Split the full roll string into parts and operators (+, -)
local function splitParts(s)
  local parts = {}
  local i = 1
  while i <= #s do
    local c = s:sub(i,i)
    if c == "+" or c == "-" then
      table.insert(parts, c)
      i = i + 1
    elseif c == " " then
      i = i + 1
    else
      local j = s:find("[%+%-]", i)
      if j then
        table.insert(parts, trim(s:sub(i, j-1)))
        i = j
      else
        table.insert(parts, trim(s:sub(i)))
        break
      end
    end
  end
  return parts
end
end


-- Helper function to escape special characters for URLs
-- Capitalize first letter
local function urlEncode(str)
local function capitalize(s)
    return str:gsub("([^%w%-%.%_%~])", function(c)
  return (s:gsub("^%l", string.upper))
        return string.format("%%%02X", string.byte(c))
    end)
end
end


-- Parse a single die expression and extract components
-- Parse an individual part into prefix, dice, and qualifiers
local function parseDieExpression(expr)
local function parsePart(part)
    local result = {
  local s = trim(part)
        original = expr,
  local prefixCount, prefixFlag
        count = "",
  local diceCount, diceFaces
        sides = "",
  local qualifiers = {}
        modifiers = "",
 
        damageTypes = {},
  -- Extract qualifiers in [brackets]
        hasEdge = false,
  local qualStr = s:match("^(.-)%[([^%]]+)%]$")
        hasProf = false
  if qualStr then
    }
    s = trim(s:match("^(.-)%["))
   
     for q in qualStr:gmatch("([^ ]+)") do
    -- Remove whitespace
      table.insert(qualifiers, q)
    expr = trim(expr)
   
    -- Extract damage types in brackets
    local damageTypePattern = "%[([^%]]+)%]"
     for damageType in expr:gmatch(damageTypePattern) do
        table.insert(result.damageTypes, trim(damageType))
     end
     end
    expr = expr:gsub(damageTypePattern, "")
  end
   
 
    -- Check for edge (@f) and proficiency (@p) modifiers
  -- Extract parenthesized prefix, e.g. (2@p) or (@f)
     if expr:match("@f") then
  local pref = s:match("^%(([%d]*@%a+)%)")
        result.hasEdge = true
  if pref then
        expr = expr:gsub("%(?@f%)?", "1")
     local num, flag = pref:match("^(%d*)@(%a+)")
    prefixCount = tonumber(num) or 1
    prefixFlag = flag
    s = s:gsub("^%b()", "", 1)
  else
    -- Pure prefix without dice
    local pure = s:match("^@(%a+)$")
    if pure then
      prefixCount = 1
      prefixFlag = pure
      s = ""
     end
     end
   
  end
    if expr:match("@p") then
 
        result.hasProf = true
  -- Extract dice, e.g. 2d6 or d8
        expr = expr:gsub("%(?(%d*)@p%)?", function(num)
  if s:match("^d%d+") then
            return num ~= "" and num or "1"
    diceCount = 1
        end)
    diceFaces = s:match("^d(%d+)")
    end
  elseif s:match("^%d+d%d+") then
   
     local cnt, faces = s:match("^(%d+)d(%d+)")
    -- Parse basic die notation (XdY with optional modifiers)
    diceCount = tonumber(cnt)
     local count, sides, modifiers = expr:match("^(%d*)d(%d+)(.*)$")
    diceFaces = faces
     if count and sides then
  end
        result.count = count ~= "" and count or "1"
 
        result.sides = sides
  return prefixCount, prefixFlag, diceCount, diceFaces, qualifiers
        result.modifiers = trim(modifiers or "")
end
 
-- Main entry for #invoke:Dice|d|<roll>|<type>
function p.d(frame)
  local fullRoll = frame.args[1] or ""
  local typ = frame.args[2] or "none"
  local parts = splitParts(fullRoll)
  local quickParts = {}
  local content = {}
 
  for _, part in ipairs(parts) do
     if part == "+" or part == "-" then
      table.insert(quickParts, part)
      table.insert(content, " " .. part .. " ")
     else
     else
        -- Handle standalone modifiers like @p[memory]
      local prefixCount, prefixFlag, diceCount, diceFaces, qualifiers = parsePart(part)
         if expr:match("^@p") then
      -- Build quick-roll (ignore flags)
            result.hasProf = true
      if diceCount then
            result.isStandaloneProf = true
         table.insert(quickParts, diceCount .. "d" .. diceFaces)
      end
 
      -- Add prefix template when type is not 'none'
      if prefixFlag and typ ~= "none" and diceCount then
        local tpl = "{{" .. string.upper(prefixFlag)
        if prefixCount and prefixCount ~= 1 then
          tpl = tpl .. "|" .. prefixCount
         end
         end
    end
        tpl = tpl .. "}}"
   
        table.insert(content, tpl)
    return result
      end
end


-- Generate quick roll version (simplified for dice.run)
      -- Build dice link
local function generateQuickRoll(diceExpr)
      if diceCount then
    local parts = {}
        local displayDice = (diceCount == 1) and ("d" .. diceFaces) or (diceCount .. "d" .. diceFaces)
   
        local linkLabel = displayDice
    -- Split by + and - while preserving operators
         -- Embed prefix in label when no type and no qualifiers
    local segments = {}
         if prefixFlag and typ == "none" and #qualifiers == 0 then
    local current = ""
          linkLabel = (prefixCount or 1) .. string.upper(prefixFlag) .. displayDice
    local i = 1
    while i <= #diceExpr do
         local char = diceExpr:sub(i, i)
         if char == "+" or char == "-" then
            if current ~= "" then
                table.insert(segments, {op = (#segments == 0 and "" or "+"), expr = trim(current)})
                current = ""
            end
            table.insert(segments, {op = char, expr = ""})
        else
            current = current .. char
         end
         end
         i = i + 1
         local link = "[https://dice.run/#/d/" .. diceCount .. "d" .. diceFaces .. " " .. linkLabel .. "]"
    end
        table.insert(content, link)
    if current ~= "" then
      elseif prefixFlag and not diceCount and typ ~= "none" then
        table.insert(segments, {op = (#segments == 0 and "" or "+"), expr = trim(current)})
        -- Pure prefix only for non-none type
    end
        table.insert(content, "{{" .. string.upper(prefixFlag) .. "}}")
   
      end
    for _, segment in ipairs(segments) do
 
        if segment.expr ~= "" then
      -- Add qualifier labels
            local parsed = parseDieExpression(segment.expr)
      if qualifiers and #qualifiers > 0 then
            if parsed.count ~= "" and parsed.sides ~= "" then
        for _, q in ipairs(qualifiers) do
                local quickDie = parsed.count .. "d" .. parsed.sides
          table.insert(content, "{{L|" .. capitalize(typ) .. "|" .. capitalize(q) .. "}}")
                table.insert(parts, segment.op .. quickDie)
            elseif parsed.isStandaloneProf then
                -- Skip standalone proficiency modifiers in quick roll
            else
                -- Handle numeric constants
                local num = segment.expr:match("^(%d+)")
                if num then
                    table.insert(parts, segment.op .. num)
                end
            end
         end
         end
      end
     end
     end
   
  end
    local result = table.concat(parts, " ")
 
    return trim(result:gsub("^%+", ""))
  -- Assemble quick-roll and content
end
  local quickRoll = table.concat(quickParts, " ")
  local inner = table.concat(content)


-- Generate formatted output based on type
  -- Build final span
local function generateFormattedOutput(diceExpr, diceType)
  local span = html.create('span')
     if not diceType or diceType == "" or diceType == "none" then
     :addClass('dice')
        -- Simple format for no type
     :attr('data-full-roll', fullRoll)
        return "[https://dice.run/#/d/" .. urlEncode(generateQuickRoll(diceExpr)) .. "]"
     :attr('data-quick-roll', quickRoll)
    end
    :attr('data-type', typ)
      
     :wikitext(inner)
    local parts = {}
    local segments = {}
    local current = ""
    local i = 1
   
    -- Split expression into segments
    while i <= #diceExpr do
        local char = diceExpr:sub(i, i)
        if char == "+" or char == "-" then
            if current ~= "" then
                table.insert(segments, {op = (#segments == 0 and "" or " + "), expr = trim(current)})
                current = ""
            end
            if char == "+" and #segments > 0 then
                table.insert(segments, {op = " + ", expr = ""})
            elseif char == "-" then
                table.insert(segments, {op = " - ", expr = ""})
            end
        else
            current = current .. char
        end
        i = i + 1
     end
    if current ~= "" then
        table.insert(segments, {op = (#segments == 0 and "" or " + "), expr = trim(current)})
    end
   
    for _, segment in ipairs(segments) do
        if segment.expr ~= "" then
            local parsed = parseDieExpression(segment.expr)
            local partText = ""
           
            if parsed.count ~= "" and parsed.sides ~= "" then
                local quickDie = parsed.count .. "d" .. parsed.sides
                local displayDie = (parsed.count == "1" and "d" or parsed.count) .. parsed.sides
               
                if parsed.hasEdge then
                    partText = "{{F}}[https://dice.run/#/d/" .. urlEncode(quickDie) .. " " .. displayDie .. "]"
                elseif parsed.hasProf then
                    local profNum = parsed.count ~= "1" and parsed.count or ""
                    partText = "{{P|" .. profNum .. "}}[https://dice.run/#/d/" .. urlEncode(quickDie) .. " " .. displayDie .. "]"
                else
                    partText = "[https://dice.run/#/d/" .. urlEncode(quickDie) .. " " .. quickDie .. "]"
                end
               
                -- Add damage type templates
                for _, damageType in ipairs(parsed.damageTypes) do
                    local typeWords = {}
                    for word in damageType:gmatch("%S+") do
                        table.insert(typeWords, word:gsub("^%l", string.upper))
                    end
                    partText = partText .. " {{L|" .. (diceType:gsub("^%l", string.upper)) .. "|" .. table.concat(typeWords, " ") .. "}}"
                end
               
            elseif parsed.isStandaloneProf then
                partText = "{{P}}"
                for _, damageType in ipairs(parsed.damageTypes) do
                    local typeWords = {}
                    for word in damageType:gmatch("%S+") do
                        table.insert(typeWords, word:gsub("^%l", string.upper))
                    end
                    partText = partText .. " {{L|" .. (diceType:gsub("^%l", string.upper)) .. "|" .. table.concat(typeWords, " ") .. "}}"
                end
            else
                -- Handle numeric constants
                local num = segment.expr:match("^(%d+)")
                if num then
                    partText = num
                end
            end
           
            if partText ~= "" then
                table.insert(parts, segment.op .. partText)
            end
        elseif segment.op ~= "" then
            -- Add standalone operators
            table.insert(parts, segment.op)
        end
    end
   
    local result = table.concat(parts, "")
     return trim(result:gsub("^ %+ ", ""))
end


-- Main function to process dice input
  return span:allDone()
function p.d(frame)
    local diceInput = frame.args[1] or ""
    local diceType = frame.args[2] or "none"
   
    if diceInput == "" then
        return ""
    end
   
    local quickRoll = generateQuickRoll(diceInput)
    local formattedOutput = generateFormattedOutput(diceInput, diceType)
   
    -- Handle special display cases
    local displayText = formattedOutput
    if diceInput:match("%(2@p%)d4") and not (diceType and diceType ~= "" and diceType ~= "none") then
        displayText = "[https://dice.run/#/d/" .. urlEncode(quickRoll) .. " 2Pd4]"
    end
   
    return '<span class="dice" data-full-roll="' .. diceInput .. '" data-quick-roll="' .. quickRoll .. '" data-type="' .. diceType .. '">' .. displayText .. '</span>'
end
end


return p
return p

Revision as of 23:15, 19 June 2025

Documentation for this module may be created at Module:Dice/doc

-- Module:Dice
-- Processes dice input strings and outputs HTML spans with roll links, templates, and data attributes

local p = {}
local html = mw.html

-- Trim whitespace from both ends
local function trim(s)
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end

-- Split the full roll string into parts and operators (+, -)
local function splitParts(s)
  local parts = {}
  local i = 1
  while i <= #s do
    local c = s:sub(i,i)
    if c == "+" or c == "-" then
      table.insert(parts, c)
      i = i + 1
    elseif c == " " then
      i = i + 1
    else
      local j = s:find("[%+%-]", i)
      if j then
        table.insert(parts, trim(s:sub(i, j-1)))
        i = j
      else
        table.insert(parts, trim(s:sub(i)))
        break
      end
    end
  end
  return parts
end

-- Capitalize first letter
local function capitalize(s)
  return (s:gsub("^%l", string.upper))
end

-- Parse an individual part into prefix, dice, and qualifiers
local function parsePart(part)
  local s = trim(part)
  local prefixCount, prefixFlag
  local diceCount, diceFaces
  local qualifiers = {}

  -- Extract qualifiers in [brackets]
  local qualStr = s:match("^(.-)%[([^%]]+)%]$")
  if qualStr then
    s = trim(s:match("^(.-)%["))
    for q in qualStr:gmatch("([^ ]+)") do
      table.insert(qualifiers, q)
    end
  end

  -- Extract parenthesized prefix, e.g. (2@p) or (@f)
  local pref = s:match("^%(([%d]*@%a+)%)")
  if pref then
    local num, flag = pref:match("^(%d*)@(%a+)")
    prefixCount = tonumber(num) or 1
    prefixFlag = flag
    s = s:gsub("^%b()", "", 1)
  else
    -- Pure prefix without dice
    local pure = s:match("^@(%a+)$")
    if pure then
      prefixCount = 1
      prefixFlag = pure
      s = ""
    end
  end

  -- Extract dice, e.g. 2d6 or d8
  if s:match("^d%d+") then
    diceCount = 1
    diceFaces = s:match("^d(%d+)")
  elseif s:match("^%d+d%d+") then
    local cnt, faces = s:match("^(%d+)d(%d+)")
    diceCount = tonumber(cnt)
    diceFaces = faces
  end

  return prefixCount, prefixFlag, diceCount, diceFaces, qualifiers
end

-- Main entry for #invoke:Dice|d|<roll>|<type>
function p.d(frame)
  local fullRoll = frame.args[1] or ""
  local typ = frame.args[2] or "none"
  local parts = splitParts(fullRoll)
  local quickParts = {}
  local content = {}

  for _, part in ipairs(parts) do
    if part == "+" or part == "-" then
      table.insert(quickParts, part)
      table.insert(content, " " .. part .. " ")
    else
      local prefixCount, prefixFlag, diceCount, diceFaces, qualifiers = parsePart(part)
      -- Build quick-roll (ignore flags)
      if diceCount then
        table.insert(quickParts, diceCount .. "d" .. diceFaces)
      end

      -- Add prefix template when type is not 'none'
      if prefixFlag and typ ~= "none" and diceCount then
        local tpl = "{{" .. string.upper(prefixFlag)
        if prefixCount and prefixCount ~= 1 then
          tpl = tpl .. "|" .. prefixCount
        end
        tpl = tpl .. "}}"
        table.insert(content, tpl)
      end

      -- Build dice link
      if diceCount then
        local displayDice = (diceCount == 1) and ("d" .. diceFaces) or (diceCount .. "d" .. diceFaces)
        local linkLabel = displayDice
        -- Embed prefix in label when no type and no qualifiers
        if prefixFlag and typ == "none" and #qualifiers == 0 then
          linkLabel = (prefixCount or 1) .. string.upper(prefixFlag) .. displayDice
        end
        local link = "[https://dice.run/#/d/" .. diceCount .. "d" .. diceFaces .. " " .. linkLabel .. "]"
        table.insert(content, link)
      elseif prefixFlag and not diceCount and typ ~= "none" then
        -- Pure prefix only for non-none type
        table.insert(content, "{{" .. string.upper(prefixFlag) .. "}}")
      end

      -- Add qualifier labels
      if qualifiers and #qualifiers > 0 then
        for _, q in ipairs(qualifiers) do
          table.insert(content, "{{L|" .. capitalize(typ) .. "|" .. capitalize(q) .. "}}")
        end
      end
    end
  end

  -- Assemble quick-roll and content
  local quickRoll = table.concat(quickParts, " ")
  local inner = table.concat(content)

  -- Build final span
  local span = html.create('span')
    :addClass('dice')
    :attr('data-full-roll', fullRoll)
    :attr('data-quick-roll', quickRoll)
    :attr('data-type', typ)
    :wikitext(inner)

  return span:allDone()
end

return p