Fandom

WoWWiki

USERAPI tinsertbeforeval

Redirected from Tinsertbeforeval

104,634pages on
this wiki
Add New Page
Talk0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

This page documents a user-defined function that you can copy and paste into your addon. Replace <PREFIX> with your AddOn's prefix to avoid conflicts between different versions of these functions.
User defined functions < tinsertbeforeval
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 Edit

 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"

CodeEdit

 -- 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

Also on Fandom

Random Wiki