Difference between revisions of "Module:LexiSorting"
From Istaria Lexica
Line 39: | Line 39: | ||
local input = frame.args[1] | local input = frame.args[1] | ||
− | |||
local delimiter = frame.args[2] | local delimiter = frame.args[2] | ||
local replaceDelimiterWith = frame.args[3] | local replaceDelimiterWith = frame.args[3] | ||
Line 52: | Line 51: | ||
end | end | ||
− | + | if replaceDelimiterWith==nil then | |
replaceDelimiterWith=delimiter | replaceDelimiterWith=delimiter | ||
end | end | ||
− | + | ||
for str in string.gmatch(input,"([^" ..delimiter.. "]+)") do | for str in string.gmatch(input,"([^" ..delimiter.. "]+)") do | ||
table.insert(t, p.trim(str)) | table.insert(t, p.trim(str)) | ||
Line 64: | Line 63: | ||
for i,v in ipairs(t) do | for i,v in ipairs(t) do | ||
if s ~= "" then | if s ~= "" then | ||
− | if( | + | if(replaceDelimiterWith=="%s") then replaceDelimiterWith=" " end |
− | s=s.. | + | s=s..replaceDelimiterWith..v |
else | else | ||
s=v | s=v |
Revision as of 03:56, 16 March 2024
Documentation for this module may be created at Module:LexiSorting/doc
--[[ LexiSorting is a set of functions which can be used to sort stuff. ]] local p={} local function anyTypesComparator( a, b ) local type1, type2 = type(a), type(b) local num1, num2 = tonumber(a), tonumber(b) if ( num1 ~= nil) and (num2 ~= nil) then -- Number or numeric string return num1 < num2 -- Numeric compare elseif type1 ~= type2 then -- Different types return type1 < type2 -- From here on, types are known to match elseif type1 == "string" then -- Non-numeric string return string.lower(a)< string.lower(b) -- Case-insensitive compare elseif type1 == "boolean" then return a and not b -- Booleans else -- What's left: function, table, thread, userdata, ? return string.lower(tostring(a)) < string.lower(tostring(b)) -- String representation compare, case-insensitive end end function p.trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end --[[ Can be used to sort a string of values. You can provide a delimiter (defaults to whitespace) frame = the MediaWiki's frame table Returns the sorted string or an empty one if no string was provided ]] function p.parseandsort( frame ) if frame == nil or frame == "" then return "" end -- frame is not given, this is an error. Return a blank string to avoid script errors. local input = frame.args[1] local delimiter = frame.args[2] local replaceDelimiterWith = frame.args[3] local t={} local s="" if input == nil or input == "" then return "" end -- nothing to do if delimiter==nil then delimiter="%s" end if replaceDelimiterWith==nil then replaceDelimiterWith=delimiter end for str in string.gmatch(input,"([^" ..delimiter.. "]+)") do table.insert(t, p.trim(str)) end table.sort(t,anyTypesComparator) for i,v in ipairs(t) do if s ~= "" then if(replaceDelimiterWith=="%s") then replaceDelimiterWith=" " end s=s..replaceDelimiterWith..v else s=v end end return p.trim(s) end return p