Module:CommonFunctions

From Elwiki
Revision as of 00:39, 3 April 2022 by Ritsu (talk | contribs)

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 splitting string to a table.
function split (inputstr, sep)
    if sep == nil then
            sep = ",%s"
    end
    local t={}
    for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
            table.insert(t, str)
    end
    return t
end