Table Helpers

Miscellaneous table helper functions.

tinsertbeforeval(tab, valBefore, val) boolRemoved = tremovebyval(tab, val) num = tcount(tab) tcopy(to, from)

Note that tinsertbeforeval and tremovebyval iterate over the table to find their targets; they can be quite slow compared to regular inserts/deletes.

Examples
local tab = { "alice", "charles" } tinsertbeforeval(tab, "charles", "bob"); &rarr; tab: "alice", "bob", "charles" tinsertbeforeval(tab, "alice", "zeta"); &rarr; tab: "zeta", "alice", "bob", "charles"

bool = tremovebyval(tab, "zeta"); &rarr; bool = true bool = tremovebyval(tab, "zeta"); &rarr; bool = false

tab2["foo"]="bar"; tab2["abc"]="xyz"; myCount = tcount(tab2); &rarr; myCount = 2

tcopy(tab2, tab); &rarr; tab2: ["foo"]="bar", ["abc"]="xyz", [1]="alice", [2]="bob", [3]="charles"

Code
-- tinsertbeforeval: insert a value before another value (given only values) --  assumes integer-indexed table, or "before" loses its meaning function &lt;PREFIX&gt;_tinsertbeforeval(tab, valBefore, val) for k,v in ipairs(tab) do     if(v==valBefore) then table.insert(tab, k, val); return; end end -- print("insertbeforeval: Could not find \""..valBefore.."\". Appending last."); table.insert(tab, val); end -- tremovebyval: remove a table row given its value function &lt;PREFIX&gt;_tremovebyval(tab, val) for k,v in pairs(tab) do     if(v==val) then table.remove(tab, k); return true; end end return false; end -- tcount: count table members even if they're not indexed by numbers function &lt;PREFIX&gt;_tcount(tab) local n = #tab if (n == 0) then for _ in pairs(tab) do       n = n + 1 end end return n end -- tcopy: recursively copy contents of one table to another function &lt;PREFIX&gt;_tcopy(to, from)  -- "to" must be a table (possibly empty) for k,v in pairs(from) do     if(type(v)=="table") then to[k] = {} &lt;PREFIX&gt;_tcopy(to[k], v); else to[k] = v;     end end end