Module:Utilities: Difference between revisionsGive feedback
Jump to navigation
Jump to search
m get_slot_color colors can now have prefix/postfix removed, allowing for dynamically editing the color |
No edit summary |
||
| (19 intermediate revisions by 6 users not shown) | |||
| Line 26: | Line 26: | ||
--round_to_significant_figures(12345.6789, 3) -- Output: 12300 | --round_to_significant_figures(12345.6789, 3) -- Output: 12300 | ||
--round_to_significant_figures(0.0012345, 2) -- Output: 0.0012 | --round_to_significant_figures(0.0012345, 2) -- Output: 0.0012 | ||
--round_to_significant_figures(-98765, 4) -- Output: -98760 | --round_to_significant_figures("-98765", 4) -- Output: -98760 | ||
function p.round_to_sig_fig( | --round_to_significant_figures("foobar", 4) -- Output: foobar | ||
function p.round_to_sig_fig(input_value, n) | |||
num = tonumber(input_value) | |||
if num == nil then | |||
return input_value | |||
end | |||
if num == 0 then | if num == 0 then | ||
return 0 | return 0 | ||
| Line 105: | Line 111: | ||
local slot_colors = { | local slot_colors = { | ||
["Weapon"] = { | ["Weapon"] = { | ||
hex = " | hex = "c8761c", | ||
rgb = " | rgb = "200, 118, 28", | ||
hsl = " | hsl = "31, 75%, 45%", | ||
cmyk = "0%, | cmyk = "0%, 41%, 86%, 22%" | ||
}, | }, | ||
["Armor"] = { | ["Armor"] = { | ||
hex = " | hex = "6f8724", | ||
rgb = " | rgb = "198, 248, 114", | ||
hsl = "82, | hsl = "82, 91%, 71%", | ||
cmyk = " | cmyk = "20%, 0%, 54%, 3%" | ||
}, | }, | ||
["Tech"] = { | ["Tech"] = { | ||
hex = " | hex = "ba5ca6", | ||
rgb = " | rgb = "186, 92, 166", | ||
hsl = " | hsl = "313, 41%, 55%", | ||
cmyk = " | cmyk = "0%, 51%, 11%, 27%" | ||
} | } | ||
} | } | ||
| Line 148: | Line 155: | ||
slot = frame.args[1] | slot = frame.args[1] | ||
color_format = frame.args[2] | color_format = frame.args[2] | ||
no_wrap = frame.args[ | no_wrap = frame.args["no_wrap"] | ||
debug_mode = frame.args["debug_mode"] | debug_mode = frame.args["debug_mode"] | ||
end | end | ||
-- Validate arguments | -- Validate arguments | ||
if slot == nil then return "'slot' parameter must be provided" end | if slot == nil or slot == "" then return "'slot' parameter must be provided" end | ||
if color_format == nil then color_format = "hex" end | if color_format == nil or color_format == "" then color_format = "hex" end | ||
if no_wrap == nil then no_wrap = false end | if no_wrap == nil or no_wrap == 'false' or no_wrap == "" then no_wrap = false else no_wrap = true end | ||
if debug_mode == nil then debug_mode = false end | if debug_mode == nil or debug_mode == 'false' or debug_mode == "" then debug_mode = false end | ||
local slot_data = slot_colors[slot] | local slot_data = slot_colors[slot] | ||
| Line 168: | Line 175: | ||
-- Add prefix and postfix wrapping | -- Add prefix and postfix wrapping | ||
if no_wrap then | if not no_wrap then | ||
-- Retrieve prefix and postfix | -- Retrieve prefix and postfix | ||
prefix = color_formats[color_format]['prefix'] | prefix = color_formats[color_format]['prefix'] | ||
| Line 181: | Line 188: | ||
end | end | ||
return color | return color | ||
end | |||
function p.remove_trailing_colon(frame) | |||
local str = frame.args[1] or "" | |||
-- Remove trailing colon | |||
return (str:gsub(":$", "")) | |||
end | |||
function p.process_variables(frame) | |||
-- Get arguments | |||
local string_key = frame.args[1] or '' | |||
local item_name = frame.args[2] or '' | |||
-- Load required modules | |||
local lang_module = require('Module:Lang') | |||
local item_data_module = require('Module:ItemData') | |||
-- Get the original text | |||
local original_text = lang_module.get_string(frame, string_key) or '' | |||
-- Process the text to replace variables with their values | |||
local processed_text = original_text:gsub("{s:([^}]+)}", function(variable_name) | |||
-- Get the value from ItemData | |||
local value = item_data_module.get_prop({args = {item_name, variable_name}}) | |||
-- If value exists, remove non-number symbols (but keep + and -) | |||
if value then | |||
-- Keep only digits (0-9), plus (+), and minus (-) | |||
value = value:gsub("[^0-9+.-]", "") | |||
-- Return empty string if nothing left, otherwise return the filtered value | |||
return value ~= "" and value or variable_name | |||
else | |||
return variable_name -- Fallback to variable name if value not found | |||
end | |||
end) | |||
return processed_text | |||
end | |||
function p.contains(tbl, str) | |||
for _, v in ipairs(tbl) do | |||
if v == str then | |||
return true | |||
end | |||
end | |||
return false | |||
end | |||
-- Expands multiple of the same template in a single preprocess call | |||
-- Example: | |||
-- expand_teampltes(frame, 'HeroIcon', {hero_atlas: {'Abrams'}, hero_bebop: {'Bebop'}) | |||
-- Returns {hero_atlas: <abrams_icon_template>, hero_bebop: <bebop_icon_template>, ...} | |||
function p.expand_templates(frame, template_name, args_map) | |||
local keys = {} | |||
local strings = {} | |||
for key, args in pairs(args_map) do | |||
keys[#keys + 1] = key | |||
end | |||
for i, key in ipairs(keys) do | |||
local args = args_map[key] | |||
local parts = {"{{", template_name, "|"} | |||
for j, arg in ipairs(args) do | |||
if j > 1 then parts[#parts + 1] = "|" end | |||
parts[#parts + 1] = arg | |||
end | |||
parts[#parts + 1] = "}}" | |||
strings[i] = table.concat(parts) | |||
end | |||
local expanded = mw.text.split( | |||
frame:preprocess(table.concat(strings, "\x01")), "\x01" | |||
) | |||
local result = {} | |||
for i, key in ipairs(keys) do | |||
result[key] = expanded[i] | |||
end | |||
return result | |||
end | |||
-- Helper function | |||
-- Returns true or false depending if the page exist | |||
function p.page_exists(title_text) | |||
local title_obj = mw.title.new(title_text) | |||
return title_obj and title_obj.exists or false | |||
end | end | ||
return p | return p | ||
Latest revision as of 01:03, 20 May 2026
Overview
[edit source]Utility functions that serve any miscellaneous purpose
Functions
[edit source]get_slot_color
[edit source]Retrieve's the color of a certain slot/category in any color format (default hex), formerly known in english as Weapon, Vitality, and Spirit, though their unlocalized names are Weapon, Armor, and Tech. Utilized by Template:Color
Parameters
[edit source]- slot - slot key, options are Weapon, Armor, and Tech
- color_format - color format - Defaults to hex. Valid options are hex, rgb, hsl, cmyk
- no_wrap - (OPTIONAL) - Defaults to false. Set to true to remove prefixes and postfixes of '#' from hex, or 'rgb()', 'hsl()', and 'cmyk()' from the other formats. May be useful for altering the values dynamically
- debug_mode - (OPTIONAL) - Defaults to false. Used mostly for documentation purposes
Examples
[edit source]See examples at Template:Color
remove_trailing_colon
[edit source]Remove's the ":" character from the end of a string
Examples
[edit source]{{#invoke:Utilities|remove_trailing_colon|A Fate's Tale:}}
A Fate's Tale
process_variables
[edit source]Processes a localized string by replacing variable patterns with their corresponding values.
Parameters
[edit source]- string_key - The localization key used to retrieve the base string (via Module:Lang)
- item_name - The name of the item used to look up variable values (via Module:ItemData)
Examples
[edit source]Active Item descriptions in Template:Active Items
{{#invoke:Utilities|process_variables|upgrade_thermal_detonator_desc|Alchemical Fire}}
Throw a flask that explodes on contact, creating an area that does increasing
spirit damage per second and reduces enemy Bullet Resist.
50% less effective vs non-heroes.
local p = {};
-- "Default %hero_name% Build" --> "Default Build", or "Default Build" with -1 or +1 for spaces
function p.remove_var(input, spaces)
-- spaces =
-- -1: also remove prefixed character
-- 0 or nil: no character
-- 1: postfixed character
-- Remove text between % and % including the %
local result = input:gsub("%%.-%%", "")
-- If spaces == -1, remove the character before the removed section
if spaces ~= nil and spaces == -1 then
result = result:gsub("%s+%s*", "", 1) -- Removes the preceding space or character
-- If spaces == 1, remove the character after the removed section
elseif spaces ~= nil and spaces == 1 then
result = result:gsub("%s+", "", 1) -- Removes the postfixed space
end
-- Trim any extra whitespace
result = result:gsub("^%s*(.-)%s*$", "%1")
return result
end
--round_to_significant_figures(12345.6789, 3) -- Output: 12300
--round_to_significant_figures(0.0012345, 2) -- Output: 0.0012
--round_to_significant_figures("-98765", 4) -- Output: -98760
--round_to_significant_figures("foobar", 4) -- Output: foobar
function p.round_to_sig_fig(input_value, n)
num = tonumber(input_value)
if num == nil then
return input_value
end
if num == 0 then
return 0
end
-- Calculate the order of magnitude (log10 returns the logarithm base 10)
local order_of_magnitude = math.floor(math.log10(math.abs(num)))
-- Scale the number to move the significant digits into the integer part
local scale = math.pow(10, n - 1 - order_of_magnitude)
-- Round the scaled number and then scale it back
local rounded_num = math.floor(num * scale + 0.5) / scale
return rounded_num
end
-- If the image exists exists, return it back enclosed in brackets, else return a blank string
function p.get_image_file(image_file_name, px, link)
if (px == nil) then px = 15 end --default
if (link == nil) then link = "" end --default
image_file = mw.title.new(image_file_name)
if image_file and image_file.exists then
image_file_name = "[[" .. image_file_name .. "|" .. px .. "px|link=" .. link .. "]]"
else
image_file_name = ''
end
return image_file_name
end
function p.string_endswith(str, ending)
return ending == "" or str:sub(-#ending) == ending
end
-- Add a space before each capital letter that is not the first character
-- i.e. BulletVelocity > Bullet Velocity
-- when a string doesn't have localization, it can outputted as add_space_before_cap(unlocalized_key)
function p.add_space_before_cap(str)
local result = str:gsub("(%l)(%u)", "%1 %2")
return result:gsub("(%u)(%u%l)", " %1%2")
end
--Much room for expansion here, currently just replaces spaces with underscores essentially
--so that it can be used in a url directly
p.url_encode = function(str)
if type(str) == 'table' and str.args then
frame = str
str = frame.args[1]
end
if (str == nil) then return "First parameter must be a string" end
if (str == '') then return '' end
-- Just replaces spaces with %20
local result = string.gsub(str, " ", "%%20")
return result --must assign as local result first to grab just first returned result
end
--Creates a deepCopy of a table
function p.deep_copy(orig)
local orig_type = type(orig)
local copy
if orig_type == "table" then
copy = {}
for key, value in pairs(orig) do
copy[p.deep_copy(key)] = p.deep_copy(value)
end
setmetatable(copy, p.deep_copy(getmetatable(orig)))
else -- For non-table types, simply return the original value
copy = orig
end
return copy
end
-- Hash for color values
local slot_colors = {
["Weapon"] = {
hex = "c8761c",
rgb = "200, 118, 28",
hsl = "31, 75%, 45%",
cmyk = "0%, 41%, 86%, 22%"
},
["Armor"] = {
hex = "6f8724",
rgb = "198, 248, 114",
hsl = "82, 91%, 71%",
cmyk = "20%, 0%, 54%, 3%"
},
["Tech"] = {
hex = "ba5ca6",
rgb = "186, 92, 166",
hsl = "313, 41%, 55%",
cmyk = "0%, 51%, 11%, 27%"
}
}
-- Hash for format configuration
local color_formats = {
hex = {
prefix = "#",
postfix = ""
},
rgb = {
prefix = "rgb(",
postfix = ")"
},
hsl = {
prefix = "hsl(",
postfix = ")"
},
cmyk = {
prefix = "cmyk(",
postfix = ")"
}
}
function p.get_slot_color(slot, color_format, no_wrap, debug_mode)
if type(slot) == 'table' and slot.args then
frame = slot
slot = frame.args[1]
color_format = frame.args[2]
no_wrap = frame.args["no_wrap"]
debug_mode = frame.args["debug_mode"]
end
-- Validate arguments
if slot == nil or slot == "" then return "'slot' parameter must be provided" end
if color_format == nil or color_format == "" then color_format = "hex" end
if no_wrap == nil or no_wrap == 'false' or no_wrap == "" then no_wrap = false else no_wrap = true end
if debug_mode == nil or debug_mode == 'false' or debug_mode == "" then debug_mode = false end
local slot_data = slot_colors[slot]
if slot_data == nil then return "slot '" .. slot .. "' was not in slots_data map" end
--Retrieve the color
local color = slot_data[color_format]
if color == nil then
return "color_format '" .. color_format .. "' is not in slots_data map"
end
-- Add prefix and postfix wrapping
if not no_wrap then
-- Retrieve prefix and postfix
prefix = color_formats[color_format]['prefix']
postfix = color_formats[color_format]['postfix']
-- Add to color
color = prefix .. color .. postfix
end
-- Return result
if debug_mode then
return " " .. color
end
return color
end
function p.remove_trailing_colon(frame)
local str = frame.args[1] or ""
-- Remove trailing colon
return (str:gsub(":$", ""))
end
function p.process_variables(frame)
-- Get arguments
local string_key = frame.args[1] or ''
local item_name = frame.args[2] or ''
-- Load required modules
local lang_module = require('Module:Lang')
local item_data_module = require('Module:ItemData')
-- Get the original text
local original_text = lang_module.get_string(frame, string_key) or ''
-- Process the text to replace variables with their values
local processed_text = original_text:gsub("{s:([^}]+)}", function(variable_name)
-- Get the value from ItemData
local value = item_data_module.get_prop({args = {item_name, variable_name}})
-- If value exists, remove non-number symbols (but keep + and -)
if value then
-- Keep only digits (0-9), plus (+), and minus (-)
value = value:gsub("[^0-9+.-]", "")
-- Return empty string if nothing left, otherwise return the filtered value
return value ~= "" and value or variable_name
else
return variable_name -- Fallback to variable name if value not found
end
end)
return processed_text
end
function p.contains(tbl, str)
for _, v in ipairs(tbl) do
if v == str then
return true
end
end
return false
end
-- Expands multiple of the same template in a single preprocess call
-- Example:
-- expand_teampltes(frame, 'HeroIcon', {hero_atlas: {'Abrams'}, hero_bebop: {'Bebop'})
-- Returns {hero_atlas: <abrams_icon_template>, hero_bebop: <bebop_icon_template>, ...}
function p.expand_templates(frame, template_name, args_map)
local keys = {}
local strings = {}
for key, args in pairs(args_map) do
keys[#keys + 1] = key
end
for i, key in ipairs(keys) do
local args = args_map[key]
local parts = {"{{", template_name, "|"}
for j, arg in ipairs(args) do
if j > 1 then parts[#parts + 1] = "|" end
parts[#parts + 1] = arg
end
parts[#parts + 1] = "}}"
strings[i] = table.concat(parts)
end
local expanded = mw.text.split(
frame:preprocess(table.concat(strings, "\x01")), "\x01"
)
local result = {}
for i, key in ipairs(keys) do
result[key] = expanded[i]
end
return result
end
-- Helper function
-- Returns true or false depending if the page exist
function p.page_exists(title_text)
local title_obj = mw.title.new(title_text)
return title_obj and title_obj.exists or false
end
return p