From 4556728b9932e3f28aad19daefbab84da8376637 Mon Sep 17 00:00:00 2001 From: Emmanuel Lepage Vallee Date: Fri, 15 Jan 2016 22:46:35 -0500 Subject: [PATCH] util: Add util.table.from_sparse Go around a limitation of the lua language spec. The return value of this method guaranteed `ipairs()` correctness. Please note that both the official Lua and Luajit implementation provide a sparse table compatible `ipairs()` and __len implementation by default. --- lib/awful/util.lua | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lib/awful/util.lua b/lib/awful/util.lua index 327c5f15a..005b095ec 100644 --- a/lib/awful/util.lua +++ b/lib/awful/util.lua @@ -411,6 +411,33 @@ function util.table.crush(t, set) return t end +--- Pack all elements with an integer key into a new table +-- While both lua and luajit implement __len over sparse +-- table, the standard define it as an implementation +-- detail. +-- +-- This function remove any non numeric keys from the value set +-- +-- @tparam table t A potentially sparse table +-- @treturn table A packed table with all numeric keys +function util.table.from_sparse(t) + local keys= {} + for k,v in pairs(t) do + if type(k) == "number" then + keys[#keys+1] = k + end + end + + table.sort(keys) + + local ret = {} + for _,v in ipairs(keys) do + ret[#ret+1] = t[v] + end + + return ret +end + --- Check if a table has an item and return its key. -- @param t The table. -- @param item The item to look for in values of the table.