[added] tablex.front and tablex.key_of

This commit is contained in:
Max Cahill 2020-04-10 14:14:15 +10:00
parent 317f3f2cc7
commit b570ea7096

View File

@ -13,6 +13,11 @@ local tablex = setmetatable({}, {
--alias
tablex.join = tablex.concat
--return the front element of a table
function tablex.front(t)
return t[1]
end
--return the back element of a table
function tablex.back(t)
return t[#t]
@ -40,7 +45,6 @@ end
--find the index in a sequential table that a resides at
--or nil if nothing was found
--(todo: consider pairs version?)
function tablex.index_of(t, a)
if a == nil then return nil end
for i,b in ipairs(t) do
@ -51,6 +55,18 @@ function tablex.index_of(t, a)
return nil
end
--find the key in a keyed table that a resides at
--or nil if nothing was found
function tablex.key_of(t, a)
if a == nil then return nil end
for k, v in pairs(t) do
if a == v then
return k
end
end
return nil
end
--remove the first instance of value from a table (linear search)
--returns true if the value was removed, else false
function tablex.remove_value(t, a)
@ -73,6 +89,9 @@ function tablex.add_value(t, a)
return false
end
--note: keyed versions of the above aren't required; you can't double
--up values under keys
--helper for optionally passed random; defaults to love.math.random if present, otherwise math.random
local _global_random = math.random
if love and love.math and love.math.random then