Module:CommonFunctions: Difference between revisions

From Elwiki
No edit summary
(Undo revision 769928 by Ritsu (talk))
Tag: Undo
Line 15: Line 15:
function string.starts(String, Start)
function string.starts(String, Start)
     return string.sub(String, 1, string.len(Start)) == Start
     return string.sub(String, 1, string.len(Start)) == Start
end
function string.ends(str, ending)
  return ending == "" or str:sub(-#ending) == ending
end
end



Revision as of 13:01, 14 May 2022

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

-- in Array
function inArray(key, array)
   if array[key] ~= nil then
      return true
   end
end

function inArrayStarts(key, array)
   for k, v in pairs(array) do
      if string.starts(k, key) then return true end
   end
end

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

function string.ends(str, ending)
   return ending == "" or str:sub(-#ending) == ending
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(s, delimiter)
    if delimiter == nil then delimiter = ',' end
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

-- Title case
function titleCaseFunc( first, rest )
   return first:upper()..rest:lower()
end

function titleCase(str)
   return string.gsub(str, "(%a)([%w_']*)", titleCaseFunc)
end