Skip to content

Lua Utilities

Some useful functions for your scripts.

UniqueList

Make a list of table objects unique based a provided key.

function uniqueList(ls, key)
    local hash = {}
    local res = {}
    for _,v in ipairs(ls) do
        local test = v[key]
        if (not hash[test]) then
            res[#res+1] = v
            hash[test] = true
        end
    end
    return res
end

String truncate

function truncate(txt, len)
    if string.len(txt) > len then
        return string.sub(txt, 1, len) .. "..."
    else
        return txt
    end        
end

Find item in list matching attribute

function fromKey(ls, key, value)

    local needle
    for index, entry in pairs(ls) do 
        if entry[key] == value then 
            needle = entry 
        end
    end
    return needle

end

Split string

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

Find in list

function inList(ls, value)
    local needle = false
    for index, entry in pairs(ls) do 
        if entry == value then 
            needle = true 
        end
    end
    return needle
end