Модуль:Helpers
Материал из проекта «Повелитель Тайн Вики»
Дополнительные действия
Related
- Module:Helpers/WikiText for html and Wiki format related things.
- Module:Helpers/Debug for quick output design without having to repeatedly creating temp code.
Doc
Collection of various unrelated helper functions.
strToBool
Converts a generic string argument to a bool. This is case insensitive.
- Converts to True:
- true, 1, yes, y, on, +
- Converts to False:
- false, 0, no, n, off, -
- Converts to Nil:
- Default
trimWhitespace
Removes any and all whitespace in a string.
isWrappedInList
Checks if a string is wrapped in ul, ol, or li. Part of the wiki text rather, gonna move this.
materialiseTable
For a table from a mw.loadData(), materialiseTable converts it into a lua table.
This is for debugging purposes, used with Module:Inspect.
ternary
Ternary operation.
Parameters
- condition: Boolean
- a: Any - when the
conditionis true. - b: Any - when the
conditionis false.
splitMulti
Splits a given string to multiple substrings with the specified set of chars.
Parameters
- condition: Boolean
- str: String - The string to split.
- chars: String - Set of chars. Internally, it is
"([^" .. chars .. "]+)", it might be possible to use a set of string with enough knowledge, this is similar to RegEx.
local p = {}
function p.strToBool(s, default)
if default == nil then
default = false
end
if type(s) == "boolean" then
return s
end
if tonumber(s) ~= nil then
return s ~= tonumber(s)
elseif type(s) ~= "string" then
return nil
end
s = s:lower():match("^%s*(.-)%s*$") -- trim and lowercase
local truth_table = {
["true"] = true,
["1"] = true,
["yes"] = true,
["y"] = true,
["on"] = true,
["false"] = false,
["0"] = false,
["no"] = false,
["n"] = false,
["off"] = false,
}
if truth_table[s] ~= nil then
return truth_table[s]
else
return default
end
end
function p.trimWhitespace(s)
if s == nil then
return nil
end
return s:match("^%s*(.-)%s*$")
end
function p.isWrappedInList(s)
if s == nil then
return nil
end
s = p.trimWhitespace(s)
local a = s:sub(1, 4) == "<ul>" and s:sub(-5) == "</ul>"
local b = s:sub(1, 4) == "<ol>" and s:sub(-5) == "</ol>"
local c = s:sub(1, 4) == "<li>" and s:sub(-5) == "</li>"
return a or b or c
end
function p.materialiseTable(t) -- recursive.
if t == nil then
return nil
end
local out = {}
for k, v in pairs(t) do
if type(v) == "table" then
out[k] = p.materialiseTable(v)
else
out[k] = v
end
end
return out
end
function p.ternary(condition, a, b)
if condition then
return a
else
return b
end
end
function p.split(str, sep)
local t = {}
local pos = 1
while true do
local start_pos, end_pos = string.find(str, sep, pos, true) -- plain = true
if not start_pos then
table.insert(t, string.sub(str, pos))
break
end
table.insert(t, string.sub(str, pos, start_pos - 1))
pos = end_pos + 1
end
return t
end
function p.splitMulti(str, chars)
local result = {}
for part in string.gmatch(str, "([^" .. chars .. "]+)") do
table.insert(result, part)
end
return result
end
return p