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 )
Starts with
function startsWith(str, start)
return str:sub(1, #start) == start
end
-- Example usage:
local result1 = startsWith("Hello World", "Hello") -- returns true
local result2 = startsWith("Hello World", "World") -- returns false
local result3 = startsWith("abc", "") -- returns true
Find first
function findFirst(list, key, value)
for _, item in ipairs(list) do
if item[key] == value then
return item
end
end
return nil
end
-- Example usage:
local items = {
{id = 1, name = "apple"},
{id = 2, name = "banana"},
{id = 3, name = "orange"}
}
local result = findFirst(items, "name", "banana")
-- result will be {id = 2, name = "banana"}
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
Set value in nested table
function setLua(t, path, v)
local ptr = t
local key = last(path)
for index, segment in pairs(path) do
if segment == key then
ptr[key] = v
else
ptr = ptr[segment]
end
end
return t
end
Usage
local t = {
foo = {
bar = {
orange = 5,
apple = 3
}
}
}
log.info(t)
setLua(t, {"foo", "bar", "orange"}, 1)
log.info(t)