Skip to content

Lua Utilities

Some useful functions for your scripts.

Sorting

Sort a list by some key

t = {
   { str = 42, dex = 10, wis = 100 },
   { str = 18, dex = 30, wis = 5 }
}

table.sort(t, function (k1, k2) return k1.str < k2.str end )

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

To comma

Turn a list in to a comma delimited string

function toComma(arr)
    local str = nil
    for index, label in pairs(arr) do
        if str ~= nil then
            str = str .. ", " .. label
        else
            str = label
        end
    end
    return str
end