Difference between revisions of "Module:LexiSorting"

From Istaria Lexica

Line 40: Line 40:
 
   u=u..","..i.." "..v
 
   u=u..","..i.." "..v
 
   end
 
   end
   print(u
+
   return u end
  
  local delimiter=delimiter
+
--[[  local delimiter=delimiter
 
   local t={}
 
   local t={}
 
   local s=""
 
   local s=""
Line 67: Line 67:
 
   return s
 
   return s
 
end
 
end
 
+
]]
 
return p
 
return p

Revision as of 02:23, 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.
]]

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

--[[
Can be used to sort a string of values. You can provide a delimiter (defaults to whitespace)

arg1 = the string to be compared
arg2 = the delimiter to be used

Returns the sorted string or an empty one if no string was provided
]]
function p.sortnatural( input, delimiter )
  
  if input == nil or input == "" then return "" end -- nothing to do

  local u = ""

  for i,v in pairs(input) do
  	u=u..","..i.." "..v
  end
  return u end

--[[  local delimiter=delimiter
  local t={}
  local s=""
  
  if delimiter==nil then
    delimiter="%s"
  end
  
  for str in string.gmatch(input,"([^" ..delimiter.. "]+)") do
    table.insert(t, str)
  end
  
  table.sort(t,anyTypesComparator)
  
  for i,v in ipairs(t) do
    if s ~= "" then
      if(delimiter=="%s") then delimiter=" " end
      s=s..delimiter..v
    else
      s=v
    end
  end
 
  return s
end
]]
return p