Module:CommonFunctions: Difference between revisions

From Elwiki
No edit summary
No edit summary
Line 30: Line 30:
     local mult = 10^(numDecimalPlaces or 0)
     local mult = 10^(numDecimalPlaces or 0)
     return math.floor(num * mult + 0.5) / mult
     return math.floor(num * mult + 0.5) / mult
end
-- Implement string trim.
function trim(s)
  return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
end


-- Implement splitting string to a table.
-- Implement splitting string to a table.
function split (inputstr, sep)
function split(pString, pPattern)
    if sep == nil then
  if pPattern == nil then pPattern = "," end
            sep = ",%s"
  local Table = {}
    end
  local fpat = "(.-)" .. pPattern
    local t={}
  local last_end = 1
    for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
  local s, e, cap = pString:find(fpat, 1)
            table.insert(t, str)
  while s do
    end
      if s ~= 1 or cap ~= "" then
    return t
    table.insert(Table,cap)
      end
      last_end = e+1
      s, e, cap = pString:find(fpat, last_end)
  end
  if last_end <= #pString then
      cap = trim(pString:sub(last_end))
      table.insert(Table, trim(cap))
  end
  return Table
end
end

Revision as of 19:25, 7 April 2022

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

-- String starts
function string.starts(String, Start)
    return string.sub(String, 1, string.len(Start)) == Start
end

-- Implement sorted loop through array.
function spairs(t)
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end
    table.sort(keys)
    local i = 0
    return function()
        i = i + 1
        if keys[i] then
            return keys[i], t[keys[i]]
        end
    end
end

-- Implement merging tables
function tableMerge(first_table, second_table)
    for k,v in spairs(second_table) do first_table[k] = v end
end

-- Implement rounding.
function round(num, numDecimalPlaces)
    if numDecimalPlaces == nil then
        numDecimalPlaces = 2
    end
    local mult = 10^(numDecimalPlaces or 0)
    return math.floor(num * mult + 0.5) / mult
end

-- Implement string trim.
function trim(s)
  return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end

-- Implement splitting string to a table.
function split(pString, pPattern)
   if pPattern == nil then pPattern = "," end
   local Table = {}
   local fpat = "(.-)" .. pPattern
   local last_end = 1
   local s, e, cap = pString:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
     table.insert(Table,cap)
      end
      last_end = e+1
      s, e, cap = pString:find(fpat, last_end)
   end
   if last_end <= #pString then
      cap = trim(pString:sub(last_end))
      table.insert(Table, trim(cap))
   end
   return Table
end