WoW:USERAPI tinsertbeforeval: Difference between revisions

From AddOn Studio
Jump to navigation Jump to search
(Added a short to tcount in case the specified table is an array.)
m (→‎Code: Fixed tremovebyval)
Line 60: Line 60:
   -- tremovebyval: remove a table row given its value
   -- tremovebyval: remove a table row given its value
   function ''<PREFIX>''_tremovebyval(tab, val)
   function ''<PREFIX>''_tremovebyval(tab, val)
     for k,v in tab do
     for k,v in pairs(tab) do
       if(v==val) then
       if(v==val) then
         table.remove(tab, k);
         table.remove(tab, k);

Revision as of 01:28, 12 April 2009

This page documents a <i>user-defined function</i> that you can copy and paste into your addon. Replace PREFIX with your addon or lib prefix to avoid conflicts between different versions of these functions.

User defined functions

Table Helpers - by Mikk -


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");
 → tab: "alice", "bob", "charles"
 tinsertbeforeval(tab, "alice", "zeta");
 → tab: "zeta", "alice", "bob", "charles"
 bool = tremovebyval(tab, "zeta");
 → bool = true
 bool = tremovebyval(tab, "zeta");
 → bool = false
 tab2["foo"]="bar";
 tab2["abc"]="xyz";
 myCount = tcount(tab2);
 → myCount = 2
 tcopy(tab2, tab);
 → 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 <PREFIX>_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 <PREFIX>_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 <PREFIX>_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 <PREFIX>_tcopy(to, from)   -- "to" must be a table (possibly empty)
   for k,v in pairs(from) do
     if(type(v)=="table") then
       to[k] = {}
       <PREFIX>_tcopy(to[k], v);
     else
       to[k] = v;
     end
   end
 end